一、MyBatis接口绑定,有哪些实现方式?
接口绑定,就是在MyBatis中任意定义接口,然后把接口里面的方法和SQL语句绑定, 我们直接调用接口方法就可以,这样比起原来了SqlSession提供的方法我们可以有更加灵活的选择和设置。
// 原始方式
TestBean testBean = (TestBean) session.selectOne("com.test.TestMapper.selectByID", 1);
接口绑定有两种实现方式,一种是通过注解绑定,就是在接口的方法上面加上 @Select、@Update等注解,里面包含Sql语句来绑定;另外一种就是通过xml里面写SQL来绑定, 在这种情况下,要指定xml映射文件里面的namespace必须为接口的全路径名。当Sql语句比较简单时候,用注解绑定, 当SQL语句比较复杂时候,用xml绑定,一般用xml绑定的比较多。
1.1 通过注解实现
在接口的方法上面加上 @Select、@Update等注解,里面写Sql语句来绑定
// 这种方式不用写mapper.xml
@Select("select * from `test_table` where id = #{id}")
public TestBean selectByID(int id);
2.2 mapper.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.test.TestMapper">
<!--
id:selectById,在同一个命名空间下具有唯一性,一般是对应接口中方法
parameterType:表示参数类型
resultType:指定返回类型
#{XXX}:表示占位符
-->
<select id="selectById" parameterType="Integer" resultType="com.test.TestBean">
select * from test_table where id = #{id}
</select>
</mapper>