mybatis的批量插入操作

2024-03-22 佚名 983 mybatis;批量插入;注解;

mybatis的批量插入操作

mybatis的批量插入操作

@Repository

public interface UserMapper {

     public String tableName = "user";

     public String column = "username, password";

      

  @Insert("<script> " +

            "insert into " + tableName +

            "(" + column + ") " +

            "values " +

            "<foreach collection=\"items\" index=\"index\" item=\"item\" separator=\",\"> "

            +

            "(#{item.username},#{item.password})"

            +

            "</foreach> " +

            "</script>")

    int batchSave(@Param("items") List<User> items);

}

@InsertProvider批量插入

 

public interface UserDAO {  

    @InsertProvider(type = UserDAOProvider.class, method = "insertAll")  

    void insertAll(@Param("list") List<User> list);  

}  

public class UserDAOProvider {  

    public String insertAll(Map map) {  

        List<User> users = (List<User>) map.get("list");  

        StringBuilder sb = new StringBuilder();  

        sb.append("INSERT INTO User ");  

        sb.append("(name, age) ");  

        sb.append("VALUES ");  

    MessageFormat mf = new MessageFormat(#'{'list[{0}].name},#'{'list[{0}].age})");  

        for (int i = 0; i < users.size(); i++) {  

            sb.append(mf.format(new Object[]{i}));  

            if (i < users.size() - 1) {  

                sb.append(",");  

            }  

        }  

        return sb.toString();  

    }  


MyBatis会把UserDAO的insertAll方法中的List类型的参数存入一个Map中, 默认的key是”list”, 可以用@Param注解自定义名称, MyBatis在调用@InsertProvide指定的方法时将此map作为参数传入, 所有代码中使用List users = (List) map.get(“list”);获取list参数. 可以从代码中看出生成的SQL语句大致为:

INSERT INTO User (id, name) VALUES (#{list[0].age, #{list[0].name}), (#{list[1].age, #{list[1].name})[,(#{list[i].age #{list[i].name})]  

============

批量删除

@Delete("<script>"+

    "delete from Homeworkresult where hwrId  in"+

    "<foreach collection='hwrids' open='(' item='hwrid' separator=',' close=')'>"+

    "#{hwrid}"

    +"</foreach>"

    + "</script>")

public void batchDelByIds(@Param("hwrids") Integer[] ids);

===================

批量更新数据方法(1)

 

//注释db_filed_name :表示的是的数据库字段名字  entity_name :表示的是你的实体字段 table_name:表示你的表名

 

    @Update("<script><foreach collection = 'objs' item ='item' open='' close='' separator=';'>update table_name set db_filed_name =#{item.entity_name} where  db_filed_name =#{item.entity_name} and db_filed_name=#{item.entity_name}</foreach></script>")

    int updateBatch(@Param("objs") List<Object> objs );

 

 

批量更新数据方法(2)

 

 

    @Update({"<script> update table_name  " +

            "<trim prefix ='set' prefixOverrides=',' > " +

                "<trim prefix ='db_filed_name = case' suffix='end'>" +

                    "<foreach collection ='objs' item ='item' index = 'index'> " +

                        "when db_filed_name = #{item.entity_name} then #{item.entity_name} " +

                    "</foreach>" +

                "</trim> " +

            "</trim> " +

                "where  db_filed_name in " +

            "<foreach collection ='objs' item ='items' index ='index' separator=',' open='(' close=')'  > " +

                "#{items.entity_name} " +

            "</foreach> </script>" })

    int updateBatchName(@Param("objs") List<Object> objs);

 

 

学习总结:

由于mybatis没有提供@Mapper中@Update更新数据详细demo,现自己动手写一个关于批量更新的数据方式,做参考,

此批量更新这2种sql执行效率有待测试,但是可以明确一点的是批量更新比单条更新更快(PS:亲测过),根据测试方法2效率基于平均(32条数据平均80毫秒)在unix 4核 16G mysql 5.7。

 

 

 

 


*本文已进行版权登记,版权归属本平台,抄袭必究。

*如需转载,请联系QQ号:260341359

*文章为作者独立观点,不代表平台立场。