zoukankan      html  css  js  c++  java
  • jdbctemplate的batchUpdate使用方法

    1.Insert a batch of SQL Inserts together.

    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.BatchPreparedStatementSetter;
    
    public int[] batchInsert(List<Book> books) {
    
        return this.jdbcTemplate.batchUpdate("insert into books (name, price) values(?,?)",
         new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement ps, int i) throws SQLException {
              ps.setString(
    1, books.get(i).getName());           ps.setBigDecimal(2, books.get(i).getPrice());         }         public int getBatchSize() {           return books.size();         }     });
    }

    2.If the batch is too big, we can split it by a smaller batch size

    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter;

    public
    int[][] batchInsert(List<Book> books, int batchSize) { int[][] updateCounts = jdbcTemplate.batchUpdate( "insert into books (name, price) values(?,?)", books, batchSize, new ParameterizedPreparedStatementSetter<Book>() { public void setValues(PreparedStatement ps, Book argument) throws SQLException { ps.setString(1, argument.getName()); ps.setBigDecimal(2, argument.getPrice()); } }); return updateCounts; }

    3.With @Transactional, any failure causes the entire operation to roll back, none of the books will be added.

    @Transactional
    public int[][] batchInsert(List<Book> books, int batchSize) {
            int[][] updateCounts = jdbcTemplate.batchUpdate(
                    "insert into books (name, price) values(?,?)",
                    books,
                    batchSize,
                    new ParameterizedPreparedStatementSetter<Book>() {
                        public void setValues(PreparedStatement ps, Book argument) throws SQLException {
                            ps.setString(1, argument.getName());
                            ps.setBigDecimal(2, argument.getPrice());
                        }
                    });
            return updateCounts;
     }

    4.batchUpdate(String[] sql)

      (1) jdbcTemplate.batchUpdate(sql);

      (2) List<String> sqlList= new ArrayList<String>();

        jdbcTemplate.batchUpdate(sqlList.toArray(new String[sqlList.size()]));

  • 相关阅读:
    中标麒麟QT5编译出现:cannot find -lGL 和 collect2:error:ld returned 1 exit status 错误
    虚拟机设置静态ip【实测中标麒麟】
    selenium webdriver如何拿到页面的加载时间
    有感于去哪儿的一道笔试题
    python selenium 常见问题列表
    乙醇的webdriver实用指南java版本
    乙醇的webdriver实用指南ruby版本
    作死的自动化测试
    从龙门镖局看自动化测试
    无用的自动化测试
  • 原文地址:https://www.cnblogs.com/rookie-ray/p/11790612.html
Copyright © 2011-2022 走看看