Spring JdbcTemplate BULK INSERT and get ID at single insert

Source: Internet
Author: User
Tags bulk insert

1. Bulk Update Inserts

Jdbctemplate.batchupdate (String sql, list<object[]> Batchargs)

Object[] The length of the array is the number of arguments per record (i.e. "?" in the SQL statement). Number of)

List: How many records are inserted in total.

/** * BULK INSERT Order Details *  */public void Addbatch (list<orderdetail> orderdetails) {    list<object[]> params = New Arraylist<> ();    for (OrderDetail orderdetail:orderdetails) {        params.add (new Object[]{orderdetail.getproductname (), Orderdetail.getproductprice (),                orderdetail.getproductcount (), Orderdetail.getparentid ()});    }    Final String sql = "INSERT into Order_Detail (pro_name,pro_price,pro_count,parent_id) VALUES (?,?,?,?)";    Jdbctemplate.batchupdate (sql, params);    }

2. Single record insert get primary key ID

/** *  insert and get primary key */public int Addandgetid (order order) {    final String sql = "INSERT into orders (name, Address,createt Ime,totalprice,status) VALUES (?,?,?,?,?) ";    Keyholder keyholder = new generatedKeyHolder ();    Jdbctemplate.update (New PreparedStatementCreator () {        @Override public        PreparedStatement Createpreparedstatement (Connection Connection) throws SQLException {            PreparedStatement ps  = Connection.preparestatement (SQL, Statement.return_generated_keys);            Ps.setobject (1, Order.getname ());            Ps.setobject (2, order.getaddress ());            Ps.setobject (3, Order.getcreatetime ());            Ps.setobject (4, Order.gettotalprice ());            Ps.setobject (5, Order.getstatus ());            return PS;        }    }, Keyholder);    Return Keyholder.getkey (). Intvalue ();}

  

  

Spring JdbcTemplate BULK INSERT and get ID on single insert

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.