</pre><pre>
Package Trade.axht.java.dao;import Org.apache.commons.beanutils.beanutils;import Org.apache.commons.dbutils.queryrunner;import Trade.axht.java.conn.jdbcutils;import Java.util.*;import Java.lang.reflect.*;import java.sql.*;/** * * Base class with generics, derived classes can inherit the class with generic parameters, manipulate beans objects by reflection * @author Administrator * @param < T> */public class Dao<t> {//with generics, derived classes can inherit the class public class<t> clazz with specific beans generic parameters; @SuppressWarnings ({" Unchecked "," rawtypes "}) public DAO () {System.out.println (GetClass ());//Print Class trade.axht.java.dao.userimpl.**** Daoimpltype Type=getclass (). Getgenericsuperclass (); System.out.println (type);/** gets the base class that inherits "this class (Dao<t>)" with a specific generic or gets the base class (Object) of this class, simply speaking, who inherits dao<t> this class, at the time of loading, It will load this constructor. The object that loads the class is a derived class of dao<t>. The base class of a derived class is dao<t>, and can get the specific generics that the base class has. The JDK document description is this: Returns the type of the direct superclass that represents the entity (class, interface, base type, or void) represented by this class. If the superclass is a parameterized type, the returned object must accurately reflect the actual type parameters used in the source//code. So the final print for **/parameterizedtype parameterizedtype= (Parameterizedtype) Type;//parameterizedtype represents a parameterized type, such as Collection <String>. System.ouT.println (Parameterizedtype); Type[] Ars=parameterizedtype.getactualtypearguments ();/** returns an array of objects representing the actual type parameters of this type. is to return the type representation of the generic parameter t,v types in Collection<t,v,... >. Type is the public advanced interface for all types in the Java programming language. They include primitive types, parameterized types, array types, type variables, and base types. **/SYSTEM.OUT.PRINTLN (ARS); clazz= (Class) ars[0];//gets the first Class object of a generic parameter System.out.println (CLAZZ); System.out.println (clazz);} /** * Add, delete, change operation * @param SQL * @param args * @return */public int executeupdate (String sql,object...args) {Connection Connec Tion=jdbcutils.getconnection (); PreparedStatement preparedstatement=null;try {preparedstatement=connection.preparestatement (SQL); if (args!=null &&args.length>0) {for (int i=0;i<args.length;i++) {preparedstatement.setobject (i+1, args[i]);}} return Preparedstatement.executeupdate ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace (); return-1;} Finally {jdbcutils.releaseconnection (connection, preparedstatement, null);}} /** * Query * @param clazz * @param SQL * @param args * @return */public list<t> gEtforlist (String sql, Object ... args) {list<t> List = new arraylist<> (); Connection Connection = null; PreparedStatement preparedstatement = null; ResultSet ResultSet = null;try {//1. Get result Set connection = Jdbcutils.getconnection ();p reparedstatement = Connection.preparestatement (SQL), if (args!=null&&args.length>0) {for (int i = 0; i < args.length; i++) { Preparedstatement.setobject (i + 1, args[i]);}} ResultSet = Preparedstatement.executequery ();//2 processing results, a list of maps is obtained, and one of the map objects is a record. The key for map is the alias of the column in resultset, and the value of map is list<map<string of the column, object>> values = Handleresultsettomaplist ( ResultSet)//3. Convert List<map<string,object>> to Class object (Clazz) instance Set list<t>list = Transftermaplisttobeanlist (values);} catch (Exception e) {e.printstacktrace ();} finally {jdbcutils.releaseconnection (connection,preparedstatement, ResultSet);} return list;} Public list<t> transftermaplisttobeanlist (list<map<string, object>> values) throws Instantiationexception, illegalaccessexception, invocationtargetexception {list<t> result = new arraylist<> (); T bean = null;if (values.size () > 0) {for (map<string, object> m:values) {beans = Clazz.newinstance (); for (MAP.E Ntry<string, object> Entry:m.entryset ()) {String propertyname = Entry.getkey (); Object value = Entry.getvalue ();// Set object Properties Beanutils.setproperty (Bean, PropertyName, value) using Org.apache.commons.beanutils.BeanUtils tool class reflection;/*try { Reflectorutil.setproperty (Bean, PropertyName, value);} catch (Nosuchfieldexception | SecurityException | IllegalArgumentException e) {//TODO auto-generated catch Blocke.printstacktrace ();} */}result.add (bean);}} return result;} Public list<map<string, object>> handleresultsettomaplist (ResultSet ResultSet) throws SQLException {List <map<string, object>> values = new arraylist<> ();//Get column name list<string> columnlabels = Getcolumnlabels (ResultSet); map<string, object> map = Null;while (Resultset.next ()) {map = new HaShmap<> (); for (String columnlabel:columnlabels) {Object value = Resultset.getobject (ColumnLabel); Map.put ( ColumnLabel, value);} Values.add (map);} return values;} Private list<string> Getcolumnlabels (ResultSet rs) throws SQLException {list<string> labels = new arraylist& Lt;> (); ResultSetMetaData RSMD = Rs.getmetadata (); for (int i = 0; i < Rsmd.getcolumncount (); i++) {Labels.add (Rsmd.getcolumnlab El (i + 1));} return labels;} public int GetCount (String sql,string...id) {Connection connection=null; ResultSet Resultset=null; PreparedStatement preparedstatement=null;try {connection=jdbcutils.getconnection (); resultSet=null; Preparedstatement=connection.preparestatement (SQL), if (id!=null&&id.length>0) {for (int i=1;i<= id.length;i++) preparedstatement.setstring (i, id[i-1]);} Resultset=preparedstatement.executequery (); if (Resultset.next ()) {return resultset.getint (1);} else {return 0;}} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace (); return 0;} Finally{jdbcutils.releaseconnection (Connection, PreparedStatement, ResultSet);}}
Defines Managerdaoimpl, which inherits from DAO
Package Trade.axht.java.dao.userimpl;import Trade.axht.java.dao.dao;import Trade.axht.java.dao.managerdao;import Trade.axht.java.domain.manager;public class Managerdaoimpl extends dao<manager> {@Overridepublic int GetCount (Manager Manager) {//TODO auto-generated method stubstring sql= "Select Count (*) from Tb_manager where username=? and password=? "; return GetCount (SQL, Manager.getusername (), Manager.getpassword ());}}
Beans type of manager class
Package Trade.axht.java.domain;public class Manager {private int id;private string username;private string password; public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public Manager () {super ();//TODO auto-generated constructor stub}public Manager (int ID, string username, string password) {super (); this.id = Id;this.username = Username;this.password = password;}}
Database connection Operation class
Package Trade.axht.java.conn;import javax.sql.*;import java.sql.*;import java.util.*;import java.io.*;p ublic class jdbcutils {private static DataSource datasource=null;static{ Properties Properties=new properties (); InputStream In=jdbcutils.class.getclassloader (). getresourceasst Ream ("dbcp.properties");//load Config file try {<span style= "White-space:pre" ></span>properties.load (in); Datasource=org.apache.commons.dbcp2.basicdatasourcefactory.createdatasource (properties);//Use the database connection pool (DBCP2) to get the data source } catch (Exception e) {//TODO auto-generated catch blockSystem.out.println ("Database connection Error!"); E.printstacktrace ();}} public static Connection getconnection () {try {return datasource.getconnection ()} catch (SQLException e) {//TODO Auto-ge Nerated catch Blocke.printstacktrace (); return null;}} public static voidReleaseconnection (Connection connection,statement statement,resultset ResultSet) {if (connection!=null) {try { Connection.close ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if (statement!=null) {try {statement.close ()} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrac E ();}} if (resultset!=null) {try {resultset.close ()} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrac E ();}}}}
Database configuration file Jdcp.properties
driverclassname=com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306/blogusername=rootpassword= Brozerinitialsize=5maxidle=10maxtotal=50maxwaitmillis=5000minidle=5
The imported Package
Java JDBC Basic operations (ADD, delete, this, check) summary