mybatis的mapper动态代理

简介

  • 使用Mapper动态代理,需要创建对应的Mapper接口,Mybatis会根据接口创建对应的动态代理对象,不需要原来dao层开发那样写实现类;

mapper动态代理的四大原则和一个注意

  1. 接口方法名与mapper.xml要调用的sql语句的id一致
  2. 接口的形参类型需要与mapper.xml parameterType 一致
  3. 接口的返回值需要与mapper.xml resultType一致
  4. mappe.xml中的namespace要与接口的全包名一致
  5. 注意mapper动态代理开发中,根据返回值类型自动选择

代码演示

  • User类的部分代码
	private Integer u_id;
	private String u_username;
	private String u_password;
	private String u_sex;
	private Date u_createTime;
	private Integer u_cid;
  • Mapper接口
package com.my.mapper;

import java.util.List;

import com.my.bean.User;
import com.my.bean.UserVo;

public interface UserMapper {

	//通过id查询用户
	public User selectUserById(Integer id);
}
  • 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.my.mapper.UserMapper">
  <select id="selectUserById" parameterType="Integer" resultType="user">
    select * from user where u_id = #{id}
  </select>
</mapper>
  • Junit测试
	@Test
	public void Test1() throws IOException {
		String resource = "sqlMapConfig.xml";
		//读取配置文件
		InputStream in = Resources.getResourceAsStream(resource);
		
		//需要ssqlSessionFactoryBulider
		SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
		
		
		//创建sqlSessionfactory
		SqlSessionFactory ssf = ssfb.build(in);
		//生产一个sqlSession
		SqlSession session = ssf.openSession();
		//操作数据库
		UserMapper mapper = session.getMapper(UserMapper.class);
		
		User user = mapper.selectUserById(1);
		System.out.println(user);
	}
  • 测试结果
    在这里插入图片描述

  • 注意

    • 主配置文件中mapper的配置
<mappers>
<!--     <mapper resource="mapper/UserMapper.xml"/> -->
<!-- 	<mapper url="file:\\\D:\eclipse_workplace\sts4_workplace\ssm_mybatis\src\mapper\UserMapper.xml"/> -->
<!-- 	<mapper class="com.my.mapper.UserMapper"/> -->
<!-- 推荐使用 -->
	<package name="com.my.mapper"/>
  </mappers>
- **使用上面的方式配置时应将Mapper接口和xml文件放在同一文件夹下,否则会出现扫描不到的问题**

你可能感兴趣的:(Javaweb学习,mybatis,java,spring,mysql)