In addition to directly invoking the open source organization to provide the jar package, what I want to say today is the final version of JDBC, we need to play more practice more understanding. The most important thing is to understand. Don't say much nonsense, let's get started.
In the morning, I put the contents of yesterday, the general method of handling transactions written in the Jdbcutils tool class.
As a matter of fact, all the details of the code have been implemented. The next part of the content, in fact, is the integration of these content, the overall control.
We say DAO:
Now we want this program to be more automated, we just need to provide a connection, it can return to us an object or a set of objects, or a result. Or we provide a connection, an object, it can be automatically implemented to increase the deletion. So that's how DAO is produced.
To apply generic classes, we design DAO as the parent class for adding and removing additions and deletions that can manipulate different objects. The specific operation is done by the DAO that manipulates the concrete entity class.
Look at the code:
DAO:
Public class Dao<T> {Class<t> Clazz =NULL;@SuppressWarnings("Unchecked") Public Dao() {Type type = This. GetClass (). Getgenericsuperclass (); Parameterizedtype pt = (parameterizedtype) type; type[] types = pt.getactualtypearguments (); Clazz = (class<t>) types[0]; System.out.println (Clazz); }protectedList<t>Getgroupvalue(Connection conn, String sql, Object...args) {List<t> List =NewArraylist<t> ();//Get PreparedStatement ' s objectPreparedStatement PS =NULL;//Execute SQLResultSet rs =NULL;Try{PS = conn.preparestatement (SQL);//Set PS for(inti =0; i < args.length; i++) {Ps.setobject (i+1, Args[i]); } rs = Ps.executequery (); ResultSetMetaData RSMD = Rs.getmetadata ();intColumnCount = Rsmd.getcolumncount (); System.out.println (ColumnCount); while(Rs.next ()) {T t = clazz.newinstance (); for(inti =1; I <= ColumnCount; i++) {//ReadString columnName = Rsmd.getcolumnlabel (i); Object Columnvalue = Rs.getobject (columnName);//writeField field = Clazz.getdeclaredfield (ColumnName); Field.setaccessible (true); Field.set (t, Columnvalue); } list.add (t); } }Catch(Exception e) {E.printstacktrace (); }finally{Jdbcutils.close (RS, PS,NULL); }returnList }protectedObjectGetValue(Connection conn, String sql, Object ... args) {Object object =NULL; PreparedStatement PS =NULL; ResultSet rs =NULL;Try{//Get PreparedStatement ' s objectPS = conn.preparestatement (SQL);//Set PS for(inti =0; i < args.length; i++) {Ps.setobject (i+1, Args[i]); }//execute the SQLrs = Ps.executequery ();//Read RS if(Rs.next ()) {object = Rs.getobject (1); } }Catch(SQLException e) {//TODO auto-generated catch blockE.printstacktrace (); }finally{Jdbcutils.close (RS, PS,NULL); }returnObject }/** * getpreparealltransaction () * * @param conn * @param SQL * @param Clazz * @param args * @return * * protectedList<t>getpreparealltransaction(Connection conn, String sql, Object ... args) {List<t> List =NewArraylist<t> ();//Get PreparedStatementPreparedStatement PS =NULL;//execute the SQLResultSet rs =NULL;Try{PS = conn.preparestatement (SQL);//Set the PS for(inti =0; i < args.length; i++) {Ps.setobject (i +1, Args[i]); } rs = Ps.executequery ();//Get the ColumnnumResultSetMetaData RSMD = Rs.getmetadata ();intColumnnum = Rsmd.getcolumncount ();//Read the RS and write to an object while(Rs.next ()) {T t = clazz.newinstance (); for(inti =1; I <= columnnum; i++) {//ReadString columnName = Rsmd.getcolumnlabel (i); Object columnval = Rs.getobject (columnName);//Through the method (reflect)Propertyutils.setproperty (t, ColumnName, Columnval); } list.add (t); } }Catch(Exception e) {E.printstacktrace (); }finally{Jdbcutils.close (RS, PS,NULL); }returnList }/** * gettransacation * * @param conn * @param SQL * @param clazz * @param args * @return */ protectedTgetpreparetransaction(Connection conn, String sql, Object ... args) {T T =NULL;//Get PreparedStatement ' s objectPreparedStatement PS =NULL; ResultSet rs =NULL;Try{PS = conn.preparestatement (SQL);//Set the PSPs.setobject (1, args[0]); rs = Ps.executequery (); ResultSetMetaData RSMD = Rs.getmetadata ();intColumnnum = Rsmd.getcolumncount ();//Read and write if(Rs.next ()) {t = clazz.newinstance (); for(inti =1; I <= columnnum; i++) {//ReadString columnName = Rsmd.getcolumnlabel (i); Object Columnvalue = Rs.getobject (columnName);//writeField field = Clazz.getdeclaredfield (ColumnName); Field.setaccessible (true); Field.set (t, Columnvalue); } } }Catch(Exception e) {E.printstacktrace (); }finally{Jdbcutils.close (RS, PS,NULL); }returnT }/** * Update * * @param conn * @param SQL * @param args * @ret Urn * / protected int transactionupdate(Connection conn, String sql, Object ... args) {//Get PreparedStatement ' s objectPreparedStatement PS =NULL;//Execute the PS introws =0;Try{conn = jdbcutils.getconnection (); PS = conn.preparestatement (SQL); for(inti =0; i < args.length; i++) {Ps.setobject (i +1, Args[i]); } rows = Ps.executeupdate (); }Catch(Exception e) {E.printstacktrace (); }finally{Jdbcutils.close (PS,NULL); }//Return returnRows }}
Found that there is no difference between the method and the method we wrote earlier, just because the declaration of T is in DAO, so we do not need to declare it in the following method. It also provides a construction method that uses reflection to get the generic type of the parent class of the current object's class this.getClass().getGenericSuperClass(); , which is the type that gets all the generic types of the parent class, and there may be a value for example, there DAO<T> may be multiple values, for example, Map<K, V> through the API we find that There is no such method in the type to remove all the types inside, and it provides such a method in its subinterface.
ParameterizedType pt = (ParameterizedType) type;
getActualTypeArguments()Returns a type[] array. Here, because we know that there is a generic type, the directly indexed element of 0 is the generic type.
To create a specific action class:
Public class Userdao extends Dao<User>{ //Select function PublicObjectGetspecialvalue(Connection conn) {String sql ="SELECT COUNT (*) from users";returnGETVALUE (conn, SQL); }//Select All PublicList<user>Getalluser(Connection conn) {String sql ="SELECT * from users";returnGETPREPAREALLTRANSACTION (conn, SQL); }//select info through ID .... PublicUserGetUser(Connection Conn,intID) {String sql ="SELECT * from users WHERE id =?";returnGETPREPARETRANSACTION (conn, SQL, ID); }//delete Public int Delete(Connection Conn,intID) {String sql ="DELETE from users WHERE id =?";returnTRANSACTIONUPDATE (conn, SQL, ID);//Update Public int Update(Connection conn, user user) {String sql ="UPDATE users SET address =?" WHERE id =? ";returnTRANSACTIONUPDATE (conn, SQL, user.getaddress (), User.getid ()); }//Insert @Test Public int Insert(Connection conn, user user) {String sql ="INSERT into users (name, address, phone) VALUES (?,?,?)";introws = transactionupdate (conn, SQL, User.getname (), user.getaddress (), User.getphone ());returnRows }}
This class is used to manipulate the user class. The test will not be written here. Let's just say the constructor.
When we create Userdao, it will call Userdao's parameterless constructor by default, and because of inheritance, this Userdao constructor will call the parent DAO's constructor by default, and then follow the above steps to analyze it.
The advantage of this is that we do not have to repeat the class clazz in some of the methods to write this parameter.
DAO, even if it is finished.
So far, we're going to draw a dividing line. The previous part needs a lot of understanding. Because this is the foundation of the three major frameworks behind learning, the core. Follow this idea from Evolution 1 to eventual evolution, and write it three times in an editor, from beginning to end. I feel very necessary.
———————————————— Gorgeous split-line —————————————-
Then there are some tools available from the open source organization that will help us complete all of the above. Of course they can write better, but the core idea is the above.
Get the connection:
Recommendation: C3P0
Recommended reason: Can be configured through an XML file.
Execute SQL statement:
Dbutils ()
For specific use, refer to the Help documentation they provide.
Today is really sleepy, school worry more things, would like to give up more of this blog. But think again, if I give up, will give me later give up to bring more reasons, and I overcame. I will keep on going. Come on, young man.
The evolutionary 4--of JDBC eventually evolves