MyBatis入门(二)接口式编程

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

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

(1)编写接口

 public interface EmpDao {

     public Emp getEmp(Integer id);
}

(2)修改Mapper文件

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

(3)编写测试

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

(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]
上一篇:WPF布局管理之Canvas、InkCanvas (转)


下一篇:从iOS 11 UI Kit中谈谈iOS 11的新变化