Mybatis Mapper代理开发规范

来源:互联网 发布:华为java面试题 编辑:程序博客网 时间:2024/05/16 18:48

程序员需要编写mapper.xml
编写mapper接口需要遵循一些开发规范,这样MyBatis就可以自动生成mapper接口实现类代理对象。
规范如下:

1、在mapper.xml中namespace等于mapper接口地址

<mapper namespace="com.hl.mybatis.first.mapper.UserMapper">

2、mapper接口中的方法名与mapper.xml中statement的ID一致


3、mapper接口中的方法输入参数类型与mapper.xml中statement的parameterType指定的类型一致


4、mapper接口中的方法返回值类型与mapper.xml中statement的resultType指定的类型一致。

接口方法:

public User findUserById(int id) throws Exception;

mapper.xml映射

<select id="findUserById" parameterType="int" resultType="com.hl.myabtis.first.beas.User">select * select * FROM user WHERE id = #{id}</select>

以上规范其实是对一下代码进行统一的生成

User user = sqlSession.selectOne("test.findUserById", id);sqlSession.insert("test.insertUser", user);sqlSession.delete("test.deleteUser", id);List<User> list = sqlSession.selectList("test.findUserByNaem", name);

因为这些代码与statement的id和参数绑定在一起了,属于硬编码,不利于程序的开发和测试。