软件编程
位置:首页>> 软件编程>> java编程>> Java框架MyBatis接口编程过程解析

Java框架MyBatis接口编程过程解析

作者:不成大牛不改名  发布时间:2022-09-18 07:47:04 

标签:Java,MyBatis,接口,编程

要求:

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生成代理对象

来源:https://www.cnblogs.com/liujingche00/p/12286934.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com