介绍
使用Java怎么实现MyBatis接口编程?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
要求:
1。配置文件的命名空间名称空间指定为接口的全类名
2。配置文件中的id唯一标识与接口中的方法对应(返回值类型对应,方法名对应,参数个数和类型对应)
接口代码:
package com.bird.mybatis.dao; import com.bird.mybatis.bean.Employee; public interface  EmployeeMapper { ,public Employee  getEmpById (Integer id),, }
对应配置文件代码:
& lt; ? xml version=?.0“,编码=癠TF-8", ?祝辞,& lt; ! DOCTYPE mapper PUBLIC “-//mybatis.org//DTD mapper 3.0//EN",“http://mybatis.org/dtd/mybatis-3-mapper.dtd"比; , & lt; !——,名称空间:名称空间(若使用接口式编程,与EmployeeMapper接口全类名一致) ,id:唯一标识(与接口中的方法名对应) ,resultType:返回值类型(与对应方法的返回值对应) ,# {id}:从传递过来的参数中取出id值 ,——比;=& lt; mapper 名称空间“com.bird.mybatis.dao.EmployeeMapper"祝辞 ,& lt; select id=癵etEmpById", resultType=癱om.bird.mybatis.bean.Employee"祝辞, select id,才能last_name lastName、性别、email 得到tbl_employee where id =, # {id} ,& lt;/select> & lt;/mapper>
测试代码:
/* * *,才能MyBatis接口编程 *,才能@throws IOException ,*/,@Test ,void test2 (), throws IOException {//才能获取sqlSessionFactory对象 SqlSessionFactory 才能;ssf =, getSqlSessionFactory ();//才能获取sqlSession对象 SqlSession 才能;openSession =, ssf.openSession (); try {才能 ,,//获取接口的实现类对象 ,,EmployeeMapper mapper =, openSession.getMapper (EmployeeMapper.class); ,,Employee empById =, mapper.getEmpById (1); ,,System.out.println (empById); }finally {才能 ,,openSession.close (); ,,} ,} ,/* * *,才能获取sqlSessionFactory对象 *,才能@throws IOException ,*/,public static SqlSessionFactory  getSqlSessionFactory (), throws IOException { String 才能;resource =,“mybatis-config.xml"; InputStream 才能;is =, Resources.getResourceAsStream(资源); return 才能;new  SqlSessionFactoryBuilder () .build(是); 以前,}>总结:
1。接口编程:
原生接口:刀===比;DaoImpl
MyBatis:刀===比;Mapper.xml
2。SqlSession代表与数据库的一次会话,用完要关闭
3。SqlSession和连接都是非线程安全的,所以每次都要获取新的对象,而不能写成成员变量
4。映射器接口没有实现类,但是MyBatis生成代理对象
看完上述内容,你们掌握使用Java怎么实现MyBatis接口编程的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!
使用Java怎么实现MyBatis接口编程