接口式编程:
什么是接口式编程呢,简单的说就是面向接口编程,将mapper与接口绑定,mybatis使用接口式编程后不需要再去关联mapper调用selectOne等方法而是将mapper与接口进行绑定直接调用接口的相关方法.十分方便.
新建一个接口EmployeeMapper
package com.fish.dao;
import com.fish.mybatis.Employee;
public interface EmployeeMapper {
//根据id查询
public Employee selectEmpById(Integer id);
}
修改EmployeeMapper.xml
<?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.fish.dao.EmployeeMapper"><!--namespace改为接口的全类名-->
<!--id改为接口中相应的方法-->
<select id="selectEmpById"
resultType="com.fish.mybatis.Employee">
select id,last_name lastName,email,gender from tbl_employee where id = #{id}
</select>
</mapper>
编写测试方法
/**
* 接口式编程
* @Author ZFH
* @Date 2019年7月3日
*/
@org.junit.Test
public void test01() throws IOException {
//读取配置文件
String resource = "config/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession = sqlSessionFactory.openSession();
//调用getMapper方法获取该接口的实现类
//这里的getmapper会为接口生成一个代理对象 由代理对象去执行增删改查
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
//调用接口的相关方法
Employee selectEmpById = mapper.selectEmpById(1);
System.out.println(selectEmpById);
//关闭Session
openSession.close();
}
运行结果
Employee [id=1, lastName=张三, email=ZFH_FISH@163.COM, gender=1]