Mybatis学习2-接口编程

mybatis常使用接口编程,优点是解耦、类型检查

接口式编程步骤

1.接口式编程

原生 Dao===> DaoImp
mybatis:Mapper====>xxMapper.xml

2.SqlSession代表和数据库的一次回访,用完必须关闭

3.SqlSession和connetion一样非线程安全,每次使用都应该获取新的对象

4.mapper接口没有实现类,但mybatis会为接口生成一个代理对象

(将接口和xml进行绑定)
EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);

5.两个重要配置文件:

mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等...系统运行信息
sql映射文件:保存了每一个sql语句的映射信息将sql抽取出来。

项目文件结构如下

在这里插入图片描述

1.mybatis-config.xml同上、EmployeeMapper.xml如下

namespace:名称空间;指定为接口的全类名
select中标签改成接口名

<?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">
	<select id="getEmpById" resultType="com.mybatis.bean.Employee">
	select id,last_name lastName,gender,email from employee where id = #{id}
	</select>
</mapper>
```

编写接口


public interface EmployeeMapper {
	public Employee getEmpById(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.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 employee where id = #{id}
</select>
<select id="selectEmp" resultType="com.mybatis.bean.Employee">
select id,last_name lastName,gender,email from employee where id = #{id}
</select>

</mapper>
@Test
	public void test01() throws IOException{
		//1.获取sqlSessionFactory
		SqlSessionFactory sqlSessionFactory = getsqlSessionFactory();
		//2.获取sqlSession对象
		SqlSession opSession = sqlSessionFactory.openSession();
		try{
		//3.获取接口的实现对象
		//mybatis为接口自动创建一个代理对象,代理对象去执行增删改查
		EmployeeMapper mapper = opSession.getMapper(EmployeeMapper.class);
		Employee employee = mapper.getEmpById(1);
//		System.out.println(mapper.getClass());
		System.out.println(employee);
		}
		finally{
			opSession.close();
		}
		
	}
发布了15 篇原创文章 · 获赞 0 · 访问量 121

猜你喜欢

转载自blog.csdn.net/weixin_38235865/article/details/103742880