/ **
* In the Web development struts framework, number of pages of data are stored in the database will be packaged in a formbean object
* In these data into the database, need to be taken out formbean median in the inserted in the database that is very troublesome
* So I devised this method, only need a sql statement (sql statement and the database field names must be in exactly the same order of fields can be casual)
* And a good package data object.
* This method of data submission page into the database, there is a great convenience.
* Here insert the primary key, primary key value should also contain an object that encapsulated
* Idea: The main is the sql statement, analysis, parsing out the field names you want to insert, in the use of reflective technology will set the value to the preparedStatement object.
* @ Param sql
* @ Param obj
* @ Return
* @ Throws Exception
* /
public int insert (String sql, Object obj) throws Exception (
if (obj == null) (
return 0;
)
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String [] fieldNames = resolveSQL (sql);
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
for (int i = 0; i <fieldNames.length; i + +) (
Object o = valueFromObject (fieldNames [i], obj);
PreparedStatementSetValue (ps, o, i +1);
)
return ps.executeUpdate ();
) finally (
jdbcUtil.free (rs, ps, conn);
)
)
================================================== ===============
package daoUtil.daoTemplate;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import jdbcUtil.JdbcUtil;
import daoUtil.PrimaryKeyer;
import daoUtil.RowMapper;
/ **
* To write jdbc program is clearly to know
* Only the sql statements in the program and its parameter values are agents of change
* The remaining code is almost similar to the (access connection, close connection)
* Here I write jdbc previous procedure a bit to improve
* Will get connection and close the connection of the program code to a template class to do
* Write jdbc program, call the appropriate method of template class, passing in sql statement, and its parameter values
* This greatly simplifies the jdbc program, has brought us convenience
* The new version of the program will continue to update the next day, eager to javaeye lot to me pointing inside the master
* @ Author kevin.wangwei
* Email: wanwei.234 @ 163.com
* 2010-1-30
* /
public class DAOTemplate (
/ ** jdbc utility class * /
private JdbcUtil jdbcUtil = JdbcUtil.getInstance ();
/ **
* Database delete operation
* @ Param sql statement sql delete operation
Delete operation * @ param args an array of sql statement parameter values
* @ Return number of records to delete
* @ Throws SQLException
* /
public int delete (String sql, Object [] args) throws SQLException (
if (args == null | | args.length == 0) (
return 0;
)
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
for (int i = 0; i <args.length; i + +) (
ps.setObject (i +1, args [i ]);// Here we should call the following PreparedStatementSetValue method
/ / However, can also be written like this, but it can not deal with null values
)
return ps.executeUpdate ();
) finally (
jdbcUtil.free (rs, ps, conn);
)
)
/ **
* Database update operation
* @ Param sql statement sql update operation
* @ Param args sql statement to an array of parameter values
* @ Return number of records updated
* @ Throws SQLException
* /
public int update (String sql, Object [] args) throws SQLException (
if (args == null | | args.length == 0) (
return 0;
)
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
for (int i = 0; i <args.length; i + +) (
ps.setObject (i +1, args [i]);
)
return ps.executeUpdate ();
) finally (
jdbcUtil.free (rs, ps, conn);
)
)
/ **
* A database query operation uses reflection to give package sql statement parameter assignment
* @ Param sql queries sql statement
* @ Param args an array of numeric deletion sql statement
* @ Return the result object
* @ Throws SQLException
* /
public Object find (String sql, Object [] args, RowMapper rowMapper) throws SQLException (
if (args == null | | args.length == 0) (
return 0;
)
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
for (int i = 0; i <args.length; i + +) (
try (
PreparedStatementSetValue (ps, args [i], i +1);
) Catch (Exception e) (
e.printStackTrace ();
)
)
rs = ps.executeQuery ();
Object obj = null;
while (rs.next ()) (
obj = rowMapper.rowMapping (rs);
)
return obj;
) finally (
jdbcUtil.free (rs, ps, conn);
)
)
/ **
* Get number of records in the table
* @ Param sql sql statement
* @ Param args array of parameters
* @ Return number of records in the table
* @ Throws SQLException
* /
public int getRecordCount (String sql, Object [] args) throws SQLException (
if (args == null | | args.length == 0) (
return 0;
)
int count = 0;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
for (int i = 0; i <args.length; i + +) (
ps.setObject (i +1, args [i]);
)
rs = ps.executeQuery ();
if (rs.next ()) (
count = rs.getInt (1);
)
) finally (
jdbcUtil.free (rs, ps, conn);
)
return count;
)
/ **
* Based on a database table, find all the records in the table
* @ Param tableName the table to query
* @ Return number of records in the table
* @ Throws SQLException
* /
public int getRecordCount (String tableName) throws SQLException (
if (tableName == null | | tableName.equals ("")){
return 0;
)
int count = 0;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try (
conn = jdbcUtil.getConnection ();
String sql = "select count (*) from" + tableName;
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
if (rs.next ()) (
count = rs.getInt (1);
)
) finally (
jdbcUtil.free (rs, ps, conn);
)
return count;
)
/ **
* Database insert operations (this is the use of callback technology interface by the caller to give the primary key assignment)
* @ Param sql insert sql statement
* @ Param args into a few
* @ Param primaryIndex primary key positions in the sql statement (less than -1 express the view that the data do not need to insert the primary key automatically generated)
* @ Return number of records inserted
* @ Throws Exception
* /
public int insert (String sql, Object [] args, int primaryKeyIndex, PrimaryKeyer primaryKeyer) throws Exception (
if (args == null | | args.length == 0) (
return 0;
)
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
if (primaryKeyIndex <=- 1) (
for (int i = 0; i <args.length; i + +) (
try (
PreparedStatementSetValue (ps, args [i], i +1);
) Catch (Exception e) (
e.printStackTrace ();
)
)
) else if (primaryKeyIndex> -1 & & primaryKeyIndex <args.length) (
for (int i = 0; i <args.length; i + +) (
if (i == primaryKeyIndex) (
PreparedStatementSetValue (ps, primaryKeyer.getPrimaryKey (), i +1);
/ / ps.setObject (i +1, primaryKeyer.getPrimaryKey ());
) else (
PreparedStatementSetValue (ps, args [i], i +1);
)
)
) else (
throw new IllegalArgumentException ( "Set the primary key location is incorrect!");
)
return ps.executeUpdate ();
) finally (
jdbcUtil.free (rs, ps, conn);
)
)
/ **
* In the Web development struts framework, number of pages of data are stored in the database will be packaged in a formbean object
* In these data into the database, need to be taken out formbean median in the inserted in the database that is very troublesome
* So I devised this method, only need a sql statement (sql statement and the database field names must be in exactly the same order of fields can be casual)
* And a good package data object.
* This method of data submission page into the database, there is a great convenience.
* Here insert the primary key, primary key value should also contain an object that encapsulated
* Idea: The main is the sql statement, analysis, parsing out the field names you want to insert, in the use of reflective technology will set the value to the preparedStatement object.
* @ Param sql
* @ Param obj
* @ Return
* @ Throws Exception
* /
public int insert (String sql, Object obj) throws Exception (
if (obj == null) (
return 0;
)
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String [] fieldNames = resolveSQL (sql);
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
for (int i = 0; i <fieldNames.length; i + +) (
Object o = valueFromObject (fieldNames [i], obj);
PreparedStatementSetValue (ps, o, i +1);
)
return ps.executeUpdate ();
) finally (
jdbcUtil.free (rs, ps, conn);
)
)
/ **
* Find all the records meet the requirements (which also uses the callback interface technology, by the calling program to determine what object the result set)
* @ Param sql query sql statement
* @ Param args query parameters
* @ Param rowMapper result set mapper
* @ Return Collection Record Set
* @ Throws SQLException
* /
public Collection ObjectList (String sql, Object [] args, RowMapper rowMapper) throws SQLException (
if (args == null | | args.length == 0) (
return null;
)
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Collection list = null;
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
for (int i = 0; i <args.length; i + +) (
ps.setObject (i +1, args [i]);
)
list = new ArrayList ();
rs = ps.executeQuery ();
while (rs.next ()) (
Object obj = rowMapper.rowMapping (rs);
list.add (obj);
)
) finally (
jdbcUtil.free (rs, ps, conn);
)
return list;
)
/ **
* Based on the JavaBean corresponding to the table of Class (using reflective technology will result set set to the JavaBean object)
* Package as a result of the query object to return JavaBean
* @ Param sql query sql statement
* @ Param args query parameters
* @ Param javaBeanClass JavaBean of the Class
* @ Return Returns access to JavaBean objects
* @ Throws Exception
* /
public Object find (String sql, Object [] args, Class javaBeanClass) throws Exception (
if (args == null | | args.length == 0) (
return 0;
)
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
for (int i = 0; i <args.length; i + +) (
ps.setObject (i +1, args [i]);
)
rs = ps.executeQuery ();
String [] names = jdbcUtil.getResultSetFieldName (rs);
Object obj = null;
while (rs.next ()) (
obj = rowMapper (javaBeanClass, rs, names);
)
return obj;
) finally (
jdbcUtil.free (rs, ps, conn);
)
)
/ **
* Based on the JavaBean corresponding to the table of the Class (the above method of overloaded methods, using a different implementation mechanisms)
* The query results into a package that contains a collection of JavaBean objects to return
* @ Param sql query sql statement
* @ Param args query parameters
* @ Param javaBeanClass javaBeanClass JavaBean of the Class
* @ Return record set
* @ Throws Exception
* /
public Collection ObjectList (String sql, Object [] args, Class javaBeanClass) throws Exception (
if (args == null | | args.length == 0) (
return null;
)
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Collection list = null;
try (
conn = jdbcUtil.getConnection ();
ps = jdbcUtil.scrollReadOnlyResultSet (sql, conn);
for (int i = 0; i <args.length; i + +) (
ps.setObject (i +1, args [i]);
)
list = new ArrayList ();
rs = ps.executeQuery ();
String [] names = jdbcUtil.getResultSetFieldName (rs);
while (rs.next ()) (
Object obj = rowMapper (javaBeanClass, rs, names);
list.add (obj);
)
) finally (
jdbcUtil.free (rs, ps, conn);
)
return list;
)
/ **
* This method is through reflection to the corresponding database table set the value of the object javaBean
* The JavaBean object must have a no-argument constructor
* @ Param clazz javabean superclass
* @ Param rs result set the database
* @ Return Object Object
* @ Throws Exception
* /
private Object rowMapper (Class clazz, ResultSet rs, String [] names) throws Exception (
Object obj = clazz.newInstance ();
for (int i = 0; i <names.length; i + +) (
String columnName = toUpperCaseFirstLetterForSet (names [i]);
Method [] m = clazz.getMethods ();
for (int j = 0; j <m.length; j + +) (
String methodName = m [j]. GetName ();
if (columnName.equals (methodName)) (
m [j]. invoke (obj, rs.getObject (i +1));
break;
)
)
)
return obj;
)
/ **
* Convert a string to an uppercase letter
* @ Param name
* @ Return
* /
private String toUpperCaseFirstLetterForSet (String name) (
if (name! = null & & name.length ()> 0) (
return "set" + name.substring (0,1). toUpperCase () + name.substring (1);
)
return "";
)
/ **
* This is reflective approach to packaging sql statement to the PreparedStatement parameter assignment
* @ Param ps
* @ Param obj the object array
* @ Param index the index parameter location
* @ Throws Exception
* /
private void PreparedStatementSetValue (PreparedStatement ps, Object obj, int index) throws Exception (
String name = getMethodName (obj);
Method [] m = ps.getClass (). GetMethods ();
for (int i = 0; i <m.length; i + +) (
String methodName = m [i]. GetName ();
if (name.equals (methodName)) (
/ / System.out.println (methodName +"===========");
m [i]. invoke (ps, index, obj);
break;
)
)
)
/ **
* Access to the array through the reflection of each element type,
* To gain PreparedStatement object setxxx Method Name
* @ Param obj sql statement parameter values
* @ Return PreparedStatement object name of the method to invoke setxxx
* /
private String getMethodName (Object obj) (
if (obj == null) (
return null;
)
/ / System.out.println (obj +"===========");
String className = obj.getClass (). GetName ();
String [] names = className.split ( "\ \.");
className = names [names.length-1];
if (className.equalsIgnoreCase ( "Integer")) (
className = "Int";
)
className = "set" + className;
return className;
)
/ **
* From the sql statement, we need to parse out the field name
* @ Param sql must be a valid sql insert statements (preferably not to use the alias)
* @ Return an array of field names
* /
private String [] resolveSQL (String sql) (
sql = sql.toLowerCase ();
int left_brackets = sql.indexOf ("(");
int right_brackets = sql.indexOf (")");
String fieldString = sql.substring (left_brackets +1, right_brackets);
String [] fieldNames = fieldString.split (",");
return fieldNames;
)
/ **
* Based on the data field names from the package out in the field object that corresponds to the value of the
* Through the reflection with the get method to obtain
* @ Param fieldName
* @ Return
* @ Throws InvocationTargetException
* @ Throws IllegalAccessException
* @ Throws Exception
* /
private Object valueFromObject (String fieldName, Object formBean) throws Exception (
String methodName = toUpperCaseFirstLetterForGet (fieldName);
Method [] methods = formBean.getClass (). GetMethods ();
for (Method m: methods) (
String mName = m.getName ();
if (methodName.equals (mName)) (
Object value = m.invoke (formBean);
return value;
)
)
return null;
)
/ **
* Convert a string to an uppercase letter
* @ Param name
* @ Return
* /
private String toUpperCaseFirstLetterForGet (String name) (
if (name! = null & & name.length ()> 0) (
name = name.trim ();
return "get" + name.substring (0,1). toUpperCase () + name.substring (1);
)
return "";
)
)







