Fourth chapter. Conquer database
--------------------------------------------------------------------------------
Spring separates the fixed and variable parts of the data access process into two distinct classes, templates (Template) and callbacks (Callback), template control, resource management, and exception handling; callback implementation-specific parts-Create statement, binding parameters, and collating result sets. Excellent application of template method pattern (P123)
JdbcTemplate template = new JdbcTemplate (myDataSource); Structure. All Spring Dao template classes are thread-safe, you can configure a JdbcTemplate property for each DAO, or you can have the DAO class inherit Jdbcdaosupport, and then use Getjdbctemplate () in the DAO class to get to Jdb Ctemplate for database operations. The practice in the book is to add a JdbcTemplate attribute to each Dao, record a slightly different log, and actually note (P127)
The Execute () method of JdbcTemplate does not have SQL parameters, that is, there is no execute (String sql, object[] params) method, and update has only update (String sql, Obje Ct[] Params method can also specify the type of each field (through the third parameter int[] argtypes), which guarantees type safety, 130 pages said JdbcTemplate provides execute (String sql, object[) params ) is wrong. (P130)
The
JdbcTemplate class creates PreparedStatementCreator (Createpreparedstatementcreator (Connection conn)) and PreparedStatementSetter (Setvalues (PreparedStatement PS)), you need to create your own Batchpreparedstatementcreator class when you batch update:
BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter () {
public
int Getbatchsize () {return persons.size ();}
public void Setvalues (PreparedStatement
ps, int index) throws sqlexception{
person who = (person) persons.get
(index);
Ps.setint (0,person.getid (). Intvalue ());
......
}
};
Getjdbctemplate (). BatchUpdate (Sql,setter);
BatchPreparedStatementSetter Setter
= new BatchPreparedStatementSetter () {
public int getbatchsize () {return persons.size
();}
public void Setvalues (preparedstatement ps, int index) throws sqlexception{
person who = (person) persons.get (index);
Ps.setint (0,person.getid
(). Intvalue ());
......
}
};
Getjdbctemplate (). BatchUpdate
(Sql,setter);
Take the incoming list<person> batch to the database operation (P131)