mybatis mapper代理方法开发
mapper代理:程序员只需要编写mapper接口(相当于dao接口)和mapper.xml就可以了
一、mapper代理开发规范
1、mapper.xml中namespace等于mapper接口全名称(既:package+接口名)
2、mapper.java接口中的方法名和mapper.xml中statement的id一致
3、mapper.java接口中的方法输入参数类型和mapper.xml中statement的parameterType指定的类型一致。
4、mapper.java接口中的方法返回值类型和mapper.xml中statement的resultType指定的类型一致。
<mapper namespace="com.xxx.mybatis.mapper.UserMapper"> <select id="findUserById" parameterType="int" resultType="com.xxx.mybatis.po.User"> select * from t_user where id = #{id} </select> </mapper>
package com.xxx.mybatis.mapper; import com.xxx.mybatis.po.User; /** * @Title: UserMapper * @Description: * @author: marw * @date 2021/06/25 13:14:23 */ public interface UserMapper { public User findUserById(int id); }
二、在SqlMapConfig.xml中加载mapper.xml
<mapper class="com.xxx.mybatis.mapper.UserMapper"/>
三、测试
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class UserMapperTest { SqlSessionFactory sqlSessionFactory; @BeforeEach public void setUp() throws Exception { // mybatis核心配置文件 String resource = "SqlMapConfig.xml"; // 核心配置文件流 InputStream inputStream = Resources.getResourceAsStream(resource); // 根据核心配置文件,创建SqlSessionFactory对象 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test void testFindUserById() { UserMapper userMapper = sqlSessionFactory.openSession().getMapper(UserMapper.class); User user = userMapper.findUserById(3); System.out.println(user); } }