为什么使用Mapper代理开发?
在使用sql映射文件选择相应的sql语句时存在硬编码问题。
List<student> ls = sqlSession.selectList("test.selectAll");
就是一旦select标签里面的id名字发生变化那么,上述代码也需要改变,不便于后续维护。
<select id="selectAll" resultType="com.mingyu.pojo.student">
select * from student
</select>
如何使用Mapper代理?
首先我们需要在mapper文件夹下面创建一个接口接口名与相应的sql映射文件名相同在接口里面定义与select标签id名相同的方法,调用该方法就代表执行标签内部的sql语句。
public interface UserMapper {
List<student> selectAll();
}
同时mapper需要将sql映射文件和相应的接口在编译以后处于统一文件夹下,可以通过创建和接口相同的文件夹结构来实现。
同时由于sql映射文件的位置发生改变我们需要注意mybatis核心配置文件的加载映射文件的路径要更新。
此时mapper标签的名称空间要改成和接口路径相同。
<mapper namespace="com.mingyu.mapper.UserMapper">
<select id="selectAll" resultType="com.mingyu.pojo.student">
select * from student
</select>
</mapper>