Mybatis有四个核心组件:
SqlSessionFactoryBuilder(构造器):根据代码或者配置生成SqlSessionFactory.
来看我们第一个项目的工具类中的一段代码,getSessionFactory()方法用于返回一个SqlSessionFactory对象,而且是通过SqlSessionFactoryBuilder().build(inputStream)方式构建的.
public static SqlSessionFactory getSessionFactory() throws IOException {
String resource ="mybatis.cfg.xml";//配置文件
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
return sessionFactory;
}
SqlSessionFactory(工厂接口):依靠其来生成SqlSession,使用的是工厂模式.通过openSession()方法生成一个sqlSession对象.
public static SqlSession getSession() throws IOException {
SqlSessionFactory sessionFactory=getSessionFactory();
return sessionFactory.openSession();
}
SqlSession(会话):一个既可以发送SQL执行返回结果,也可以获取Mapper的接口.
顺便这几天刚好学了JUnit写几个测试.
public class TestMybatis {
SqlSession sqlSession;
UserMapper mapper;
@Before
public void getMapper() throws IOException {
sqlSession=MybatisUtil.getSession();
mapper=sqlSession.getMapper(UserMapper.class);
}
@Test
public void getUserTest() {
User user=mapper.getUser(1);
System.out.println(user.getId()+" "+user.getName());
}
@Test
public void addUserTest() {
User user=new User();
user.setName("saber");
mapper.insertUser(user);
}
@Test
public void updateUserTest() {
User user=new User();
user.setName("lance");
user.setId(2);
mapper.updateUser(user);
}
@Test
public void deleteUserTest() {
mapper.deleteUser(3);
}
@After
public void close() {
sqlSession.commit();//不要忘记提交
sqlSession.close();
}
}
来看运行结果
SQL Mapper(映射器):有一个java接口和XML或注解组成,需要给出对应的SQL的映射规则.映射器负责发送SQL去执行,并返回结果.需要注意的是当同时配置了XML和注解时,XML会覆盖注解方式.
下面是注解方式配置映射器
public interface UserMapper2 {
@Select("select * from user where id = #{id}")
public User getUser(int id);
@Insert("insert into user(id,name) values(#{id},#{name})")
public User insertUser(User user);
@Delete("delete from user where id = #{id}")
public int deleteUser(Integer id);
@Update("update user set name=#{name} where id = #{id}")
public int updateUser(User user);
}