Java框架MyBatis接口编程过程解析
2020-03-13 12:08
549 查看
要求:
1.配置文件的namespace名称空间指定为接口的全类名
2.配置文件中的id唯一标识与接口中的方法对应(返回值类型对应,方法名对应,参数个数和类型对应)
接口代码:
package com.bird.mybatis.dao; import com.bird.mybatis.bean.Employee; public interface EmployeeMapper { public Employee getEmpById(Integer id); }
对应配置文件代码:
<?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:名称空间(若使用接口式编程,与EmployeeMapper接口全类名一致) id:唯一标识(与接口中的方法名对应) resultType:返回值类型(与对应方法的返回值对应) #{id}:从传递过来的参数中取出id值 --> <mapper namespace="com.bird.mybatis.dao.EmployeeMapper"> <select id="getEmpById" resultType="com.bird.mybatis.bean.Employee"> select id,last_name lastName,gender,email from tbl_employee where id = #{id} </select> </mapper>
测试代码:
/** * MyBatis接口编程 * @throws IOException */ @Test void test2() throws IOException { //获取sqlSessionFactory对象 SqlSessionFactory ssf = getSqlSessionFactory(); //获取sqlSession对象 SqlSession openSession = ssf.openSession(); try { //获取接口的实现类对象 EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); Employee empById = mapper.getEmpById(1); System.out.println(empById); }finally { openSession.close(); } } /** * 获取sqlSessionFactory对象 * @throws IOException */ public static SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream is = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(is); }
总结:
1.接口编程:
原生接口: Dao ===> DaoImpl
MyBatis: Dao ===> Mapper.xml
2. SqlSession代表与数据库的一次会话,用完要关闭
3. SqlSession和Connection都是非线程安全的,所以每次都要获取新的对象,而不能写成成员变量
4.mapper接口没有实现类,但是MyBatis生成代理对象
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- Mybatis 源码解析二、Mapper接口的代理实现过程 MapperScannerConfigurer 解析
- myBatis接口编程,Junit测试,打印Sql执行过程
- mybatis+spring 中自动实现mapper接口调用存储过程
- TCPIP详解第1卷1.10标准化过程1.11RFC1.12标准的简单服务1.13互联网1.14实现1.15应用编程接口1.16测试网络
- mybatis源码解析(三)-SqlSession.selectOne类似方法调用过程
- mybatis源码解析(四)-Mapper方法调用过程
- MyBatis 以接口Interface的方式编程
- [转载]解析Java类和对象的初始化过程_J2EE_Java开发_软件开发-编程-IT资源网
- MyBatis 源码分析 - 映射文件解析过程
- Mybatis拦截器执行过程解析
- 面向接口设计和编程——(面向对象、面向接口、面向过程、面向实现) --转载
- Mybatis(2)基于命名空间的接口编程方式
- mybatis_初始化过程源码解析
- Java编程思想解析 第1章 对象导论 1.2 每个对象都有一个接口
- Mybatis学习(2)以接口的方式编程
- mybatis基础教程之二:接口的方式编程
- SpringBoot集合Mybatis过程解析
- SpringBoot整合mybatis简单案例过程解析
- Mybatis接口编程方式实现增删改查
- mybatis实战教程(mybatis in action)之二:以接口的方式编程