MyBatis入门(二)接口式编程

在  MyBatis入门(一) 的基础之上编写接口

将接口和Mapper文件进行绑定,会为接口创建一个代理对象,代理对象去执行增删改查

(1)编写接口

1 public interface EmpDao {
2 
3     public Emp getEmp(Integer id);
4 }

(2)修改Mapper文件

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper
3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="com.eu.dao.EmpDao">
6   <select id="getEmp" resultType="com.eu.pojo.Emp">
7     select id,last_name lastName,gender,email from Emp where id = #{id}
8   </select>
9 </mapper>

(3)编写测试

 1   @Test
 2     public  void testMapper02() throws IOException {
 3         //1.获取SqlSessionFactory对象
 4         String resource = "conf/mybatis-config.xml";
 5         InputStream inputStream = Resources.getResourceAsStream(resource);
 6         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 7         //2.获取SqlSession对象
 8         SqlSession session = sqlSessionFactory.openSession();
 9         try {
10             //3.获取接口的实现类对象
11             EmpDao empDao = session.getMapper(EmpDao.class);
12             Emp emp = empDao.getEmp(1);
13             System.out.println(emp);
14         } finally {
15           session.close();
16         }
17     }

(4)运行结果

DEBUG 04-14 23:01:47,690 ==>  Preparing: select id,last_name lastName,gender,email from Emp where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 04-14 23:01:47,801 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 04-14 23:01:47,842 <==      Total: 1  (BaseJdbcLogger.java:145) 
Emp [id=1, lastName=张三, geder=null, email=we.com]

 

posted @ 2019-04-14 22:58  司徒二条  阅读(175)  评论(0编辑  收藏  举报