Spring provides us with a unified encapsulation of JDBC, which, unlike other Orm, is the encapsulation of the JDBC API, which is equivalent to the Java bean we write ourselves, without encapsulating the object model (such as encapsulating the PO as Pojo). It preserves the primitive nature of JDBC data Objects, has a great degree of flexibility, and is extremely performance-efficient.We know that it is best to use PreparedStatement when doing incremental operations, which saves the cost of compiling SQL statements from the database server. Spring also provides support for incremental operations, while the BatchpreparedstatementseThe Tter interface is its core.First look at Batchpreparedstatementse.Some operations are defined in the Tter interface.public interface Batchpreparedstatementsetter{ public int getbatchsize ();public void Setvalues (PreparedStatement ps,int i);}This interface is the callback interface used by the JdbcTemplate class. Each operation in a batch operation uses the same SQL statement, and the interface sets a specific value for the placeholder in the SQL statement.public int getbatchsize (); To return the size of a batchpublic void Setvalues (PreparedStatement ps,int i);Used to set a value for PreparedStatement.Parameter description:PS: We are going to set the value of the PreparedStatementI: In this batch, the index in which the operation is being performed, is calculated from 0.Take the batch update as an example, what we need to do is to implement Batchpreparedstatementse first.Tter interface, and then call JdbcTemplate's BatchUpdate (sql,setter) operation, parameter SQL is a precompiled statement, setter is BatchpreparedstatementseAn instance of tter. Here is a piece of code I wrote:
|
public void batchinsertrows (String sql,final list<object[]> dataSet) throws exception{
BatchpreparedstatementseTter setter=new BatchpreparedstatementseTter () {
public int getbatchsize () {
return Dataset.size ();
}
public void Setvalues (PreparedStatement ps,int i) {
object[] obj = Dataset.get (i);
int nextid = Getnextid (); try{
Ps.setlong (1,nextid);
Ps.setlong (2,integer.parseint (obj[0].tostring ())); Ps.setlong (3,integer.parseint (obj[1].tostring ()));
Ps.setstring (4, (String) obj[2]);}
catch (Exception e) { E.printstacktrace ();
}
}
};
jdbctemplate.batchupdate (sql,setter);
}
|
Spring Bulk Update data----batchpreparedstatementsetter