When integrating MyBatis in Spring Boot before, the annotation configuration method was adopted. I believe many people still prefer this elegant method. I have also received feedback and questions from many readers and friends, mainly focusing on annotations for various scenarios. How to use, the following is an example of usage in several common situations.
Parameters
The insertion operation implemented in the preceding section is implemented in the following through several different ways of passing parameters.
Use @Param
In the previous integration example, we have used this simplest way of passing parameters, as follows:
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
This method is easy to understand, @Param
the definition in name
corresponds to the SQL #{name}
, age
corresponds to the SQL #{age}
.
Use Map
The following code uses a Map object as a container for passing parameters:
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
int insertByMap(Map<String, Object> map);
For the parameters required in the Insert statement, we only need to fill in the content of the same name in the map, as shown in the following code:
Map<String, Object> map = new HashMap<>();
map.put("name", "CCC");
map.put("age", 40);
userMapper.insertByMap(map);
user target audience
In addition to Map objects, we can also directly use ordinary Java objects as parameters for query conditions. For example, we can directly use User objects:
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insertByUser(User user);
In this way, the , in the statement correspond to the and attributes in the User object, respectively #{name}
.#{age}
name
age