MyBatis学习笔记(二)- 接口式编程

MyBatis 的 HelloWorld 的进阶

注意:本次操作是在上一个笔记的基础之上

工程目录如下:

1. 创建一个 EmployeeMapper 的接口

public interface EmployeeMapper {
	
	public Employee getEmpById(Integer id);

}

2. 修改 Mapper 文件

<mapper namespace="www.xq.mybatis.dao.EmployeeMapper">
<!-- 
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值

public Employee getEmpById(Integer id);
 -->
	<select id="getEmpById" resultType="www.xq.mybatis.bean.Employee">
		select id,last_name lastName,email,gender from tbl_employee where id = #{id}
	</select>
</mapper>

3. 测试

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();
		}

	}

mybatis HelloWorld 小结

  1. 接口式编程
    原生: Dao ====> DaoImpl
    mybatis: Mapper ====> xxMapper.xml

  2. SqlSession代表和数据库的一次会话;用完必须关闭;

  3. SqlSession和connection一样她都是非线程安全。每次使用都应该去获取新的对象。

  4. mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象。
    (将接口和xml进行绑定)
    EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);

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

猜你喜欢

转载自blog.csdn.net/qq_42130468/article/details/85332248
今日推荐