企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # 开发规范 Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。 Mapper接口开发需要遵循以下规范: 1. Mapper.xml文件中的namespace与mapper接口的类路径相同。 2. Mapper接口方法名和Mapper.xml中定义的每个statement的id相同 3. Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同 4. Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同 # 编码 我们创建mapper包 然后在mapper包下创建UserMapper.java ~~~ package mapper; import pojo.User; public interface UserMapper { // 遵循四个原则 // 接口方法名 == User.xml中的id名字 // 返回值类型与Mapper.xml文件中返回值类型要一致 // 方法入参类型与Mapper.xml中入参类型要一致 // 命名空间绑定此接口 public User findUserById(Integer id); } ~~~ 我们把User.xml的namespace改下 ~~~ <mapper namespace="mapper.UserMapper"> ~~~ 然后我们写个测试 ~~~ @Test public void testMapper() throws Exception { // 加载核心配置文件 String resource = "SqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); // 创建SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // SqlSession帮我生成一个实现类(给接口) UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findUserById(10); System.out.println(user); } ~~~