美文网首页
MyBaits —— 通过调用接口映射sql语句

MyBaits —— 通过调用接口映射sql语句

作者: 桑鱼nicoo | 来源:发表于2020-03-11 21:38 被阅读0次

创建过程参考上篇

1、编写mapper接口

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

2、编写sql映射文件,配置了每一个sql以及sql的封装规则

<?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">
<!--namespace:名称空间,对应mapper接口的全类名-->
<mapper namespace="com.sangyu.mapper.EmployeeMapper">
    <!--
    id:唯一标识
    resultType:返回值类型,对应的Bean类型
    {#id}:从传递过来的参数中取出id值
    select 中增加别名,防止因为mysql中的字段与bean中的不对应,导致该字段查询出来的结果为空
    -->
    <select id="getEmpId" resultType="com.sangyu.bean.Employee">
    select id,last_name lastName,email,gender from tbl_employee where id = #{id}
  </select>
</mapper>

3、查询过程:

  1. 根据xml全局配置文件创建一个SqlSessionFactory对象,其中包含数据源一些运行环境信息,全局配置文件还注册了对应的sql映射文件
  2. 使用SqlSessionFactory获取了SqlSession对象使用它来执行增删改查,一个SqlSession 代表和数据库的一次会话,用完关闭
  3. 通过SqlSession获取接口的实现类,会为接口自动的创建一个代理对象,代理对象去执行增删改查
  4. 调用接口的方法(接口的方法会映射的具体的sql)得到查询结果
public class MyBatisTest {

    @Test
    public void Test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 根据xml创建sqlSessionFactory
        SqlSession session = sqlSessionFactory.openSession(); // 2. 从 SqlSessionFactory 中获取 SqlSession 的实例,SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
        try {
            // 3. 获取接口的实现类对象
            EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
            Employee employee = mapper.getEmpById(1);
            System.out.println(employee);
        }finally {
            session.close();
        }
    }
}

相关文章

网友评论

      本文标题:MyBaits —— 通过调用接口映射sql语句

      本文链接:https://www.haomeiwen.com/subject/rckkjhtx.html