Summary of Common Ways of Springboot Integrating Mybatis Value Transfer

  • 2021-10-11 18:48:14
  • OfStack

Mode 1: Direct transmission

Interface


public interface UserMapper {
    public List<User> getUserById(int 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" >
 
<!-- Interface -->
<mapper namespace="com.lxc.springboot.mapper.UserMapper" >
    <select id="getUserById" resultType="com.lxc.springboot.domain.User">
        select * from user where id = #{id}
    </select>
</mapper>

Mode 2: @ Param by annotation

In this way, it will be used in fuzzy query, and the annotated parameters and variables in xml must be 1! (xml do not know why must use the ${} way, use the # {} way to look up the data!)
Interface


public interface UserMapper {
    public List<User> getLikeList(@Param("name")String pname);
}

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" >
 
<!-- Interface -->
<mapper namespace="com.lxc.springboot.mapper.UserMapper" >
 
    <select id="getLikeList" resultType="com.lxc.springboot.domain.User">
        select id, user, name, age, password from user where name like '%${name}%'
    </select>
 
</mapper>

Mode 3: Through Map key value pair mode

The advantage of this method is that the variable (that is, key in Map type) does not need to be associated with the field name 1, and the passed field depends on the actual needs. For this example, if you use User class as the parameter type, then you must pass all the attributes!

Interface


import com.lxc.springboot.domain.User;
import org.apache.ibatis.annotations.Param;
 
import java.util.List;
import java.util.Map;
 
public interface UserMapper {
    //  Insert data 
    public void insertUser(Map<String, Object> user);
}

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" >
 
<!-- Interface -->
<mapper namespace="com.lxc.springboot.mapper.UserMapper" >
 
    <insert id="insertUser" parameterType="hashmap">
        insert into user(user, name, age, password) values (#{userPost}, #{userName}, #{userAge}, #{userPassword})
    </insert>
</mapper>

That's all, and other ways will be used in future projects, in recording!


Related articles: