Recently, I have developed an example of writing about packaging in my spare time, and then sort out the previous ones.
public class BaseDao<T> {Connection conn;PreparedStatement st;ResultSet rs;JdbcUtil jdbcUtil = new JdbcUtil();int result = 0;private Class<T> persistentClass;@SuppressWarnings("unchecked")public BaseDaoUtil(){conn = jdbcUtil.getConnection();ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();persistentClass = (Class<T>) type.getActualTypeArguments()[0];} /** * Save* @param entity * @return */public int save(T entity) throws Exception{String sql = "INSERT INTO "+ entity.getClass().getSimpleName().toLowerCase() +" (";List<Method> list = this.matchPojoMethods(entity,"get");Iterator<Method> iter = list.iterator();Object obj[] = new Object[list.size()];int i = 0;//Split field order insert into table name(id,name,email, while(iter.hasNext()) { Method method = iter.next(); sql += method.getName().substring(3).toLowerCase() + ","; if (method.getReturnType().getSimpleName().indexOf("Date") !=-1) {SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");obj[i] = sbf.format(method.invoke(entity, new Object[]{})); }else {obj[i] = method.invoke(entity, new Object[]{}); } i++; } //Remove the last one, symbol insert insert into table name(id,name,email) values( sql = sql.substring(0, sql.lastIndexOf(",")) + ") values("; //Assemble precompiled SQL statement insert insert into table name(id,name,email) values(?,?,?, for(int j = 0; j < list.size(); j++) { sql += "?,"; } //Remove the last SQL statement, symbol insert insert into table name(id,name,email) values(?,?,?); sql = sql.substring(0, sql.lastIndexOf(",")) + ")"; //To this SQL statement splicing is completed, print the SQL statement System.out.println(sql); try { st = conn.prepareStatement(sql); for (int j = 0; j < obj.length; j++) {st.setObject(j+1, obj[j]);}result = st.executeUpdate();} catch (SQLException e) {e.printStackTrace();} jdbcUtil.getClose(rs, st, conn);return result;}/** * Delete* @param object * @return * @throws SQLException */public int deleteId(Object object) throws Exception{String sql = "delete from "+ persistentClass.getSimpleName().toLowerCase() +" where ";//Use the constructor of the subclass to obtain the specific type of the parameterized type. For example, BaseDAO<T>, that is, obtain the specific type of T. entity = persistentClass.newInstance(); //The method object that stores the primary key of Pojo (or the table being operated) Method idMethod = null; List<Method> list = this.matchPojoMethods(entity, "set"); Iterator<Method> iter = list.iterator(); //Filter the method object while(iter.hasNext()) { Method tempMethod = iter.next(); if(tempMethod.getName().indexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) { idMethod = tempMethod; } else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))){ idMethod = tempMethod; } } //The first letter is converted to lowercase sql += idMethod.getName().substring(3,4).toLowerCase()+idMethod.getName().substring(4) + " = ?"; System.out.println(sql);st = conn.prepareStatement(sql);//Judge the type of id if(object instanceof Integer) { st.setInt(1, (Integer)object); } else if(object instanceof String){ st.setString(1, (String)object); } result = st.executeUpdate();jdbcUtil.getClose(rs, st, conn);return result;}/** * Modify* @param entity * @return * @throws Exception */public int update(T entity) throws Exception{String sql = "update "+ entity.getClass().getSimpleName().toLowerCase() +" set ";List<Method> list = this.matchPojoMethods(entity, "get");//Loading parameters Object obj[] = new Object[list.size()];int i = 0;//Temporary Method object, responsible for iterating the fashion method object. Method tempMethod = null; // Since the ID is not required to be modified during modification, adding parameters in order should move the Id to the end. Method idMethod = null; Iterator<Method> iter = list.iterator(); while(iter.hasNext()) { tempMethod = iter.next(); //If the method name contains an ID string and the length is 2, it is considered an ID. if(tempMethod.getName().lastIndexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) { obj[list.size()-1] = tempMethod.invoke(entity, new Object[]{}); //Save the object of the ID field into a variable and delete it in the set. idMethod = tempMethod; iter.remove(); //If the method name is removed and the set/get string is incompatible with pojo + "id" (case insensitive), it is considered an ID } else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))) { obj[list.size()-1] = tempMethod.invoke(entity, new Object[]{}); idMethod = tempMethod; iter.remove(); } } //Move the iterative pointer to the first position iter = list.iterator(); while(iter.hasNext()) { tempMethod = iter.next(); sql += tempMethod.getName().substring(3).toLowerCase() + "= ?,"; obj[i] = tempMethod.invoke(entity, new Object[]{}); i++; } //Remove the last one, symbol sql = sql.substring(0,sql.lastIndexOf(",")); //Add condition sql += " where " + idMethod.getName().substring(3).toLowerCase() + " = ?"; //SQL splicing is completed, print SQL statement System.out.println(sql); st = conn.prepareStatement(sql); for (int j = 0; j < obj.length; j++) {st.setObject(j+1, obj[j]);} result = st.executeUpdate(); jdbcUtil.getClose(rs, st, conn); return result;}public T findById(Object object) throws Exception{String sql = "select * from "+ persistentClass.getSimpleName().toLowerCase() +" where ";//Use the constructor of the subclass to obtain the specific type of the parameterized type. For example, BaseDAO<T>, that is, obtain the specific type of T entity = persistentClass.newInstance(); //The method object that stores the primary key of Pojo (or the table being operated) Method idMethod = null; List<Method> list = this.matchPojoMethods(entity, "set"); Iterator<Method> iter = list.iterator(); //Filter the Method object while(iter.hasNext()) { Method tempMethod = iter.next(); if(tempMethod.getName().indexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) { idMethod = tempMethod; } else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))){ idMethod = tempMethod; } } //The first letter is converted to lowercase sql += idMethod.getName().substring(3,4).toLowerCase()+idMethod.getName().substring(4) + " = ?"; System.out.println(sql);st = conn.prepareStatement(sql);//Judge the type of id if(object instanceof Integer) { st.setInt(1, (Integer)object); } else if(object instanceof String){ st.setString(1, (String)object); } rs = st.executeQuery(); //Point the pointer to the first line of the iterator iter = list.iterator(); //Encapsulate while(rs.next()) { while(iter.hasNext()) { Method method = iter.next(); if(method.getParameterTypes()[0].getSimpleName().indexOf("String") != -1) { //Because in the list set, the order of the method object to be retrieved is inconsistent with the order of the database field (for example: the first method of list is setDate, and the database takes the "123" value in order) //The database fields are selected in the corresponding name. this.setString(method, entity, rs.getString(method.getName().substring(3).toLowerCase())); } else if(method.getParameterTypes()[0].getSimpleName().indexOf("Date") != -1){ this.setDate(method, entity, rs.getDate(method.getName().substring(3).toLowerCase())); }else { this.setInt(method, entity, rs.getInt(method.getName().substring(3).toLowerCase())); } } } jdbcUtil.getClose(rs, st, conn); return entity;}/** * Filter all Method objects with incoming strings in the current Pojo class and return the List collection. */ private List<Method> matchPojoMethods(T entity,String methodName) { //Get all current Pojo method objects Method[] methods = entity.getClass().getDeclaredMethods(); //List container stores all Method objects with get string List<Method> list = new ArrayList<Method>(); //Filter all Method objects with get strings in the current Pojo class and store them in the List container for(int index = 0; index < methods.length; index++) { if(methods[index].getName().indexOf(methodName) != -1) { list.add(methods[index]); } } return list; } /** * When the parameter type is String, set parameters for the entity field, corresponding to set */ public String setString(Method method, T entity, String arg) throws Exception{ return (String)method.invoke(entity, new Object[]{arg}); } /** * When the parameter type is Date, set parameters for the entity field, corresponding to set */ public Date setDate(Method method, T entity, Date arg) throws Exception{ return (Date)method.invoke(entity, new Object[]{arg}); } /** * When the parameter type is Integer or int, set parameters for the entity field, corresponding to set */ public Integer setInt(Method method, T entity, Integer arg) throws Exception{ return (Integer)method.invoke(entity, new Object[]{arg}); } }The above article BaseDao (example code) encapsulated by JDBC is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.