通过接口就能实现业务方法,(接口和xml配置文件的动态绑定)这是现在的MyBatis的一个基本使用。
前期准备
和上一章相同
步骤
1.在com.mybatis.dao 包中创建一个接口EmployeeMapper
EmployeeMapper接口中写了一个根据id查询的抽象方法
EmployeeMapper.java
package com.mybatis.dao;
import com.mybatis.bean.Employee;
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
2.修改EmployeeMapper这个xml配置文件信息
这里的namespace命名空间需要对应那个接口类的路径 : 实现这个xml和接口类进行绑定
id为接口类中的方法名称 : 实现这个selet标签和这个方法进行绑定
注意:namesapce=“com.mybatis.dao.EmployeeMapper”
id=“getEmplById”
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.mybatis.dao.EmployeeMapper">
<!--
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值
public Employee getEmpById(Integer id);
-->
<select id="getEmpById" resultType="com.mybatis.bean.Employee">
select id,last_name lastName,gender,email from tbl_employee where id = #{id}
</select>
</mapper>
3.在com.mybatis.test.MyBatisTest类中编写相应的方法
package com.mybatis.test;
import com.mybatis.bean.Employee;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* 1.接口式编程
* 原生: Dao ===> DaoImpl
* mybatis: Mapper ===> xxMapper.xml
*
* 2.SqlSession代表和数据库的一次会话;用完必须关闭
* 3.SqlSession和connection一样都是非线程安全。不能提前声明一个private SqlSession sqlSession;每次使用都应该去获取新的对象。
* 4.mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象。
* (将接口和xml进行绑定)
* EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class)
* 5.两个重要的配置文件:
* mybatis的全局配置文件,包含数据库连接池信息,事务管理器信息等...系统运行环境信息
* sql映射文件:保存了每一个sql语句的映射信息;
* 将sql抽取出来。
*/
public class MyBatisTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test01() throws IOException{
//1.获取sqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//2.获取sqlSession对象
SqlSession openSession = sqlSessionFactory.openSession();
try {
//3.获取接口的实现类对象
//会为接口自动地创建一个代理对象,代理对象去执行增删改方法
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpById(1);
System.out.println(mapper.getClass());
System.out.println(employee);
}finally {
openSession.close();
}
}
}