Detailed explanation of Mybatis (5) Mapper interface

  • 2021-07-16 02:21:16
  • OfStack

(1) Mapper Interface and Principle

Mapper formation

1. The Mapper file and Mapper interface should be placed in the same interface 2. The namespace in the Mapper file should be set to the fully qualified name of the Mapper interface 3. The operation element ID in the Mapper file corresponds to the method name of the Mapper interface

Principle of Mapper:
Dynamic agent

(2) Configuration file

userMapper.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">
<!--  For this mapper Specify 1 Individual only 1 Adj. namespace , namespace The value of is customarily set to the package name +sql Map the file name, so that you can ensure that namespace The value of is only 1 Adj. 
 For example namespace="me.gacl.mapping.userMapper" Is me.gacl.mapping( Package name )+userMapper(userMapper.xml File suffix removal )
 -->
<mapper namespace="Mybatis.domain.Mapper.UserMapper">

  <resultMap type="User" id="BaseResultMap">
  	<result column="t_id" property="id"/>
  	<result column="t_name" property="name"/>
  	<result column="t_salary" property="salary"/>
  </resultMap>
  
  <!--  Save operation  -->
  <insert id="save" useGeneratedKeys="true" keyProperty="id">
	  INSERT INTO t_user (name , salary) 	VALUES (#{name},#{salary}) 	
  </insert>
  
  <!--  Change action  -->
  <update id="update">
  	update t_user where name=#{name},salary=#{salary} where id=#{id}
  </update>
  
  <!--  Delete operation  -->
  <delete id="delete" >
  	delete from t_user where id=#{id}
  </delete>
  
  <!--  Query a single operation  --> 
  <select id="select" parameterMap="java.lang.Long" resultType="Mybatis.domain.User">
    select * from t_user where id = #{id}
  </select>

	<!--  Query multiple operations  -->
	<select id="selectAll" resultType="User">
		select id,name,salary from t_user
	</select>  
</mapper>

UserMapper.java


import java.util.List;

import Mybatis.domain.User;

public interface UserMapper {
	void save(User u);
	
	void update(User u);
	
	void delete(Long id);
	
	User select(User u);
	
	List<User> selectAll();
}

Related articles: