Mapper代理开发需要遵循的规则:

  1. 接口与对应的映射配置文件同名同目录;
  2. 映射配置文件中的namespace值等于接口的全路径;
  3. 映射配置文件中SQL声明的ID与接口中的函数名相同;
  4. 映射配置文件中SQL声明中的parameterType类型与接口函数的参数类型一致;
  5. 映射配置文件中SQL声明中的resultType类型与接口函数的返回值类型一致。

过程

  1. 创建pojo类对象并生成getter、setter、无参、有参、toString方法

  2. 导入对应Jar包

  3. 创建config的source文件夹

    1. 文件夹内创建MyBatis配置文件mybatis-config.xml

      <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
      <configuration>
        <properties resource="db.properties"></properties>
        <!-- 数据库连接配置文件路径 -->
        <environments default="development">
          <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
              <property name="driver" value="${driver}"/>
              <property name="url" value="${url}"/>
              <property name="username" value="${username}"/>
              <property name="password" value="${password}"/>
            </dataSource>
          </environment>
        </environments>
        <mappers>
          <mapper resource="com/demo/mapper/UserMapper.xml"/> 
          <!-- 类实现接口的xml配置文件路径 -->
        </mappers>
      </configuration>
      
    2. 创建数据库连接配置文件db.properties

      driver=com.mysql.cj.jdbc.Driver	#驱动名
      url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=True&characterEncoding=UTF-8	#数据库连接url
      username=root	#用户名
      password=root	#密码
      
    3. 创建pojo类所需的接口方法UserMapper.java

      package com.demo.mapper;
      
      import java.util.List;
      
      import com.demo.pojo.User;
      
      public interface UserMapper {
      
      	public User findUserById(String userid);
      	public List<User> findUserByName(String username);
      	public void insertUser(User user);
      	public void deleteUser(String userid);
      	public void updateUser(User user);
      }
      
      
    4. User类配置文件实现接口方法UserMapper.xml

      <!DOCTYPE mapper
          PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
          "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      
      <mapper namespace="com.demo.mapper.UserMapper">
        <!--  -->
      	<select id="findUserById" parameterType="java.lang.String" resultType="com.demo.pojo.User">
          <!--parameterType为键入参数类型,resultType为结果参数类型 -->
      	  SELECT * FROM user WHERE userid = #{userid}
      	</select>
      	
      	<select id="findUserByName" parameterType="java.lang.String" resultType="com.demo.pojo.User">
      	  SELECT * FROM user WHERE username like #{username}
      	</select>
      	
      	<insert id="insertUser" parameterType="com.demo.pojo.User">
      		  INSERT INTO user (userid, username, gender, birthday, height, phone, address)
        VALUES (#{userid},#{username},#{gender},#{birthday},#{height},#{phone},#{address})
      	</insert>
      	
      	<update id="updateUser" parameterType="com.demo.pojo.User">
      		  UPDATE user SET username = #{username}, gender = #{gender}, birthday = #{birthday}, 
      		  height = #{height}, phone = #{phone}, address = #{address} WHERE userid = #{userid}
      	</update>
      	
      	<delete id="deleteUser" parameterType="java.lang.String">
      		DELETE FROM user WHERE userid = #{userid}
      	</delete>
      	
      </mapper>
      
  4. 创建测试类

    package com.demo.test;
    
    import static org.junit.jupiter.api.Assertions.*;
    
    import java.io.InputStream;
    import java.util.Date;
    import java.util.List;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.jupiter.api.AfterAll;
    import org.junit.jupiter.api.AfterEach;
    import org.junit.jupiter.api.BeforeAll;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    
    import com.demo.mapper.UserMapper;
    import com.demo.pojo.User;
    
    class test {
    
      //资源名
    	static String resource = null;
      //输入流
    	static InputStream inputStream = null;
      //sql会话工厂对象
    	static SqlSessionFactory sqlSessionFactory = null;
      //sql会话对象
    	static SqlSession sqlSession = null;
      //mapper映射对象
    	static UserMapper mapper = null;
    
    	@BeforeAll
    	static void setUpBeforeClass() throws Exception {
    
    		resource = "mybatis-config.xml";
    		inputStream = Resources.getResourceAsStream(resource);
        //new SqlSessionFactoryBuilder().build(inputStream);
    		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
    	}
    
    	@AfterAll
    	static void tearDownAfterClass() throws Exception {
    	}
    
    	@BeforeEach
    	void setUp() throws Exception {
    		sqlSession = sqlSessionFactory.openSession();
    		mapper = sqlSession.getMapper(UserMapper.class);	//接口的字节码文件
    
    	}
    
    	@AfterEach
    	void tearDown() throws Exception {
    		sqlSession.close();
    	}
    
    	@Test
    	void findUserById(String userid) {
    		User user = mapper.findUserById(userid);
    		System.out.println(user);
    	}
    	
    	@Test
    	void findUserByName() {
    		List<User> users = mapper.findUserByName("%王%");
    		for(User user :users) {
    			System.out.println(user);
    		}
    	}
    	
    	@Test
    	void insertUser() {
    		Date birthday = new Date();
    		
    		User user = new User();
    		user.setUserid("110");
    		user.setUsername("test");
    		user.setGender("男");
    		user.setBirthday(birthday);
    		user.setHeight(190.0);
    		user.setPhone("110");
    		user.setAddress("广东");
    		
    		mapper.insertUser(user);
    		sqlSession.commit();
    		
    	}
    	
    	@Test
    	void updateUser() {
    		Date birthday = new Date();
    		
    		User user = new User();
    		user.setUserid("110");
    		user.setUsername("done");
    		user.setGender("男");
    		user.setBirthday(birthday);
    		user.setHeight(200.0);
    		user.setPhone("120");
    		user.setAddress("广东");
    		
    		mapper.updateUser(user);
    		sqlSession.commit();
    		
    	}
    	
    	@Test
    	void deleteUser() {
    		mapper.deleteUser("110");
    		sqlSession.commit();
    	}
    
    }
    
    

踩过的坑

  1. mybatis-config.xml中针对UserMapper.xml的配置,包路径用"/"分割。
  2. config已设置为source文件夹,因此可以直接在测试类中用resource = "mybatis-config.xml";
  3. mapper = sqlSession.getMapper(UserMapper.class); 此处应该用接口文件名+class字节码后缀(编译后)。
  4. 接口名需与xml中id名一致。

参考资料

MyBatis