MyBatis3系列__02接口式编程

时间:2023-03-08 17:38:06

hello world

MyBatis3支持面向接口编程:

具体做法如下,将helloWorld中的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.learn.dao.EmployeeMapper"> <select id="selectEmployee" resultType="com.mybatis.learn.bean.Employee"> select id, last_name lastName, gender, email from tbl_employee where id = #{id} </select> </mapper>

将namespace改为你新创建的接口的全类名,其中,接口如下所示:


package com.mybatis.learn.dao; import com.mybatis.learn.bean.Employee; public interface EmployeeMapper { public Employee getEmpById(Integer id); }

然后将测试类中的方法进行更改


@Test public void test() { //1.从 XML 中构建 SqlSessionFactory // 也可以不使用xml文件来获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.从 SqlSessionFactory 中获取 SqlSession // SqlSession session = sqlSessionFactory.openSession(); // try { // Employee employee = (Employee) // //session.selectOne("org.mybatis.example.BlogMapper.selectEmployee", 1); // System.out.println(employee); // } finally { // session.close(); // } SqlSession session = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); Employee employee = mapper.getEmpById(1); System.out.println(employee); } finally { session.close(); } }

注意:

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

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

3.mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象(将接口和xml进行绑定)

即:EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);

4.mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等...系统运行环境信息

5.sql映射文件:保存了每一个sql语句的映射信息:将sql抽取出来。