标签:pat rate property parameter 注解 foreach can desc 并且
上次面试中被问到Mybatis中使用insert后返回自增id怎么操作,当时只知道可以返回被修改的行数,并不知道可以将插入/修改的内容的主键id映射到使用的对象中,后续查阅资料才知道有这样的功能。。
User.java:
public class User {
private int id;
private String userName;
private String password;
private String realName;
// Getter & Setter
}
mapper内容:
public interface UserMapper {
void insertAll(User user);
void insertBatch(List<User> users);
}
在classpath下mapper文件夹内的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" >
<mapper namespace="com.tz.mapper.UserMapper">
<insert id="insertAll" useGeneratedKeys="true" keyProperty="id" keyColumn="id" parameterType="com.tz.model.User">
insert into `user1`(userName, password, realName)
values (#{userName}, #{password}, #{realName})
</insert>
<insert id="insertBatch" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into `user1`(userName, password, realName)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.userName}, #{item.password}, #{item.realName})
</foreach>
</insert>
</mapper>
上述两种形式:单个插入、批量插入都能插入成功并且将插入的主键id映射到对象User中,这样我们就可以使用插入的主键id进行redis缓存存储之类的操作了。
@param is a special format comment used by javadoc to generate documentation.
it is used to denote a description of the parameter (or parameters) a method can receive
要加@Param注解的话需要额外修改xml中的配置(collection)(原本collection不加@Param注解的时候是list array map三种类型):
void insertBatch(@Param("users") List<User> users);
<insert id="insertBatch" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into `user1`(userName, password, realName)
values
<foreach collection="users" item="item" index="index" separator=",">
(#{item.userName}, #{item.password}, #{item.realName})
</foreach>
</insert>
这种方法可以完成插入数据,但是并没有任何返回值映射到我们使用的实例中(以前是什么,现在就是什么)
public interface UserMapper {
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Insert("insert into `user1`(userName, password, realName) " +
"values(#{userName}, #{password}, #{realName}) ")
void insert(User user);
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Insert({
"<script>" +
"insert into `user1`(userName, password, realName)" +
"values" +
"<foreach collection=‘list‘ item=‘item‘ index=‘index‘ separator=‘,‘>" +
"(#{item.userName}, #{item.password}, #{item.realName})" +
"</foreach>" +
"</script>"
})
void insertBatchByAnnotation(List<User> users); // 可以使用int返回值,返回的是操作影响的表内行数
}
标签:pat rate property parameter 注解 foreach can desc 并且
原文地址:https://www.cnblogs.com/Tchou/p/13923586.html