您的位置:首页 > 编程语言 > Java开发

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

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java MyBatis 接口 编程