前面博客已经研究过,批量操作数据库可以很大程度上优化操作速度,昨天做的小需求中就有批量查询的使用,于是在此记录下批量操作数据库的常用代码,方便日后查询使用。这里直接粘贴代码,
批量查询操作
@Select("<script>" +
"select * from person" +
" where id in" +
" <foreach item='item' collection='list' open='(' separator=',' close=')'>" +
" #{item}" +
" </foreach>" +
"</script>")
List<Person> selectByIds(@Param("list") List<Integer> Ids);
需要理解的可能就是其中foreach语法了,而且比较关键的应该也只有collection的属性值,具体的语法讲解可以看这里:mybatis之foreach用法
批量插入操作
@Insert("<script> insert into `person` " +
"(`name`,`gender`) " +
"VALUES " +
"<foreach item='persons' collection='list' open='(' separator=',' close=')'>" +
" #{persons.name}," +
" #{persons.gender}," +
"</foreach> " +
"</script>")
@Lang(Person.class)
@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
Integer batchInsert(@Param("list") List<Person> list);
其中的@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
useGeneratedKeys=true表示使用数据库自动增长的主键,keyColumn用于指定数据库table中的主键,keyProperty用于指定传入对象的成员变量。
这个注解的意思就是,使用数据库自动增长的主键,并从table中id字段里面把数据放到传入对象的成员变量id里面。
如果我们已经在数据库表中指定了主键,那么keyColumn属性可以缺省。(所以我们的插入语句中不用插入id字段以及属性值)
批量更新
@Update({"<script>" +
"<foreach collection=\"list\" item=\"item\" separator=\";\">" +
" UPDATE" +
" person" +
" SET name = #{item.name} " +
" WHERE " +
" id = #{item.id} " +
"</foreach>" +
"</script>"})
void batchUpdateId(List<Person> list);