Application of callback in QueryRunner (45), callback queryrunner
Step 1: implement a call class:
/**
* Query with callback
*/
Public<T> T query (String SQL, MyHandler <T> mh ){
T t =Null;
// Declare conn
Connection con =Null;
Try{
Con = ds. getConnection ();
// Execute the query
Statement st = con. createStatement ();
ResultSet rs = st.exe cuteQuery (SQL );
// Let the callback execute Data encapsulation
T = mh. handler (rs );
}Catch(Exception e ){
E. printStackTrace ();
}Finally{
Try{
Con. close ();
}Catch(SQLException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}
}
ReturnT;
}
Step 2: Define callback specifications
PackageCn. itcast. dbutils;
ImportJava. SQL. ResultSet;
/**
* Receive rs result set
*@ AuthorAdministrator
*
*@ Param<T>
*/
Public InterfaceMyHandler <T> {
T handler (ResultSet rs );
}
Step 3: implement a callback
PackageCn. itcast. dbutils;
ImportJava. lang. reflect. Method;
ImportJava. SQL. ResultSet;
ImportJava. SQL. ResultSetMetaData;
ImportJava. util. ArrayList;
ImportJava. util. List;
Public ClassMyBeanListHandler <T>ImplementsMyHandler <List <T> {
PrivateClass <T> cls;
PublicMyBeanListHandler (Class <T> cls ){
This. Cls = cls;
}
PublicList <T> handler (ResultSet rs ){
List <T> list =NewArrayList <T> ();
Try{
ResultSetMetaData rsmd = rs. getMetaData ();
IntCols = rsmd. getColumnCount ();
While(Rs. next ()){
T t = cls. newInstance ();
// Obtain the column name
For(IntI = 0; I <cols; I ++ ){
String colName = rsmd. getColumnName (I + 1 );
String methodName =
"Set" + colName. substring (0, 1)
. ToUpperCase ()
+ ColName. substring (1). toLowerCase ();
// Obtain the type
String javaType = rsmd. getColumnClassName (I + 1); // = "java. lang. String ";
Try{
Method mm =
Cls. getMethod (methodName, Class.ForName(JavaType ));
Object val = rs. getObject (I + 1 );
Mm. invoke (t, val );
}Catch(Exception e ){}
}
List. add (t );
}
}Catch(Exception e ){
}
ReturnList;
}
}
Step 4: test:
@ Test
Public VoidMyutils3 (){
QueryRunner run =NewQueryRunner (performanceutils.GetDatasSource());
String SQL = "select * from users ";
List <User> cs =
Run. query (SQL,NewMyBeanListHandler <User> (User.Class));
For(User c: cs ){
System.Err. Println (">>:" + c );
}
}