mybatis有两种关联映射文件的方式
(1)第一种是直接读取映射文件
通过映射文件名称路径加上要处理的sql语句所在块的id
@Test
public void findCustomerByIdTest() throws IOException {
// 1.读取mybatis配置文件 获得一个输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
// 2.创建mybatis的sql工厂对象
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.通过工厂对象 创建sql会话
SqlSession sqlSession = sessionFactory.openSession();
// 4.通过sql会话执行相应的方法 获得结果
String mpsrc = "com.cxit.mapper.CustomerMapper.findCustomerById";
Customer cust = sqlSession.selectOne(mpsrc, 1);
// 5.打印结果
System.out.println(cust);
// 6.关闭session
sqlSession.close();
}
这种方式很直接了当,创建的sql会话对象,执行相应的方法,把要传的参数传到映射文件中(传的参数只能是一个),
当传的参数是基本类型时,在映射文件中的#{}里面可以任意写,${}里面则只能写value;
当传的参数是pojo类型时,在映射文件中的#{}里面只能写与pojo属性相对应的名称(因为要通过反射机制,进行一一对应),${}里面也要如此。
(2)第二种是通过接口关联映射文件
映射文件里的命名空间得改成接口的包.类名,
通过反射,获得一个接口字节码对象,然后通过接口字节码对象创建一个接口对象,再通过接口对象执行相应的方法。
public void findCustomerByIdTest() throws IOException {
// 1.读取mybatis配置文件 获得一个输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
// 2.创建mybatis的sql工厂对象
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.通过工厂对象 创建sql会话
SqlSession sqlSession = sessionFactory.openSession();
// 4.通过sql会话执行相应的方法 获得结果
CustomerDao dao = sqlSession.getMapper(CustomerDao.class);
Customer cust = dao.findCustomerById(1);
// 5.打印结果
System.out.println(cust);
// 6.关闭session
sqlSession.close();
}
第二种的传参机制与第一种大抵相同,只不过是换成了接口的形参接收参数,#{}与${}的处理机制与第一种的一样。