Generic DAO method

Source: Internet
Author: User

Import Java.lang.reflect.field;import Java.sql.connection;import Java.sql.databasemetadata;import Java.sql.preparedstatement;import Java.sql.resultset;import Java.sql.resultsetmetadata;import java.util.ArrayList  ;p Ublic class Rdao {/** * by indicating that the table in the database is listed * @param tableName * @return */public arraylist<string> getallcolumn (String tableName) {arraylist<string> ar = new arraylist<string> (); Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; ResultSet rs = null;//1=2 not established can only be found to list string sql = "SELECT * from" +tablename+ "where 1=2"; try {ps = conn.preparestatement (sq L); rs = Ps.executequery (); ResultSetMetaData metedata = Rs.getmetadata (); int colum = Metedata.getcolumncount (); for (int i=1;i<=colum;i++) { String columnName = Metedata.getcolumnname (i); Ar.add (ColumnName);}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS, RS);} return ar;} /** * data is listed by metadata, data type, etc. * the difference between the two can be obtained by the SQL statement query out all the listed * D can only get the single table and all the properties of the column * * @pAram TableName * @return */public arraylist<string> getallcolumns (String tableName) {arraylist<string> ar = New Arraylist<string> (); Connection conn = Baseconnection.getconnection ();    ResultSet rs = null;try {///Database metadata object, which is the database data object DatabaseMetaData dbm = Conn.getmetadata (); rs = Dbm.getcolumns (null, "%", tableName, "%"), while (Rs.next ()) {String columnName = rs.getstring ("column_name"); String ColumnType = rs.getstring ("type_name"); String datasize = rs.getstring ("Column_size"); String digits = rs.getstring ("Decimal_digits"); String nullable = rs.getstring ("nullable"); Ar.add (ColumnName);}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, RS);} return ar;} public boolean insert (Object ob) {Boolean b = false; Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; Class cl = Ob.getclass (); Field[] fi = Cl.getdeclaredfields (); Arraylist<string >col = Getallcolumn (Cl.getsimplename ()); StringBuffer sb = new StringBuffer (); StrIngbuffer sb1 = new StringBuffer () sb.append ("INSERT INTO"), Sb.append (Cl.getsimplename ()), Sb.append ("("); for (int i=1 ; I<col.size (); i++) {Sb.append (Col.get (i)); Sb1.append ("?"); if (i! = Col.size ()-1) {Sb.append (","); Sb1.append (",");}} Sb.append (") VALUES ("); Sb.append (SB1); Sb.append (")"); try {PS = conn.preparestatement (sb.tostring ()); for (int i=1;i <col.size (); i++) {for (Field Ff:fi) {if (Ff.getname (). Equals (Col.get (i))) {ff.setaccessible (true);p s.setobject (i, Ff.get (OB)); break;}}} int a = Ps.executeupdate (), if (a > 0) {b = true;}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS);} return b;} Demand is now there is a table, this table is an order form (order number, order time, order person)//20150101 zhang//from the Table Order Detail table Number of Order No.//1 KU 2//2 Qun 3// Order has a lot of data, we insert the data is inserted into the order form, and then insert the Order Detail table, and then insert the Order Detail table when you need the order number in the Orders table. public int Insertgetkey (Object ob) {int id = 0; Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; ResultSet rs = null; Class cl = Ob.getclass (); Field[] fi = Cl.getdeclaredfields (); Arraylist<string >col = Getallcolumn (Cl.getsimplename ()); StringBuffer sb = new StringBuffer (); StringBuffer sb1 = new StringBuffer (), Sb.append ("INSERT INTO"), Sb.append (Cl.getsimplename ()), Sb.append ("("); for (int I=1;i<col.size (); i++) {Sb.append (Col.get (i)); Sb1.append ("?"); if (i! = Col.size ()-1) {Sb.append (","); Sb1.append (",");}} Sb.append (") VALUES ("); Sb.append (SB1); Sb.append (")"); try {PS = conn.preparestatement (sb.tostring ()); for (int i=1;i <col.size (); i++) {for (Field Ff:fi) {if (Ff.getname (). Equals (Col.get (i))) {ff.setaccessible (true);p s.setobject (i, Ff.get (OB)); break;}}}  int a = Ps.executeupdate (), if (a > 0) {////Gets the primary key, the primary key must be incremented, and the method must be added to obtain the primary key rs = Ps.getgeneratedkeys (); if (Rs.next ()) {id = Rs.getint (1);}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS);} return ID;} Delete yourself write based on ID delete publiC Boolean Deletebyid (Class cl,int ID) {Boolean b = false;object OB = NULL; Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; Field[] fi = Cl.getdeclaredfields ();//Get all the columns in the table arraylist<string> col = getallcolumns (Cl.getsimplename ()); StringBuffer sb = new StringBuffer (), sb.append ("delete"), Sb.append ("from"); Sb.append (Cl.getsimplename ()); sb.append ("where"); Sb.append (Col.get (0)); Sb.append ("?"); try {PS = conn.preparestatement (sb.tostring ());p S.setint (1, id), int a = Ps.executeupdate (), if (a>0) {b = true;}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS);} return b;} /** * This method is not required, meaningless, directly forgotten, also gets the value of * @param ob * @return */public int updategetkey (Object ob) {int id = 0; Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; ResultSet rs = null; Class cl = Ob.getclass (); Field[] fi = Cl.getdeclaredfields (); Arraylist<string >col = Getallcolumn (Cl.getsimplename ()); StringBuffer sb = new StringBuffer (); Sb.append ("Update"); Sb.append (Cl.getsimplename ()); Sb.append ("set"); for (int i=1;i<col.size (); i++) {Sb.append ( Col.get (i)); Sb.append ("?"); if (i! = Col.size ()-1) {Sb.append (",");}} Sb.append ("where"); Sb.append (Col.get (0)); Sb.append ("=?"); try {PS = conn.preparestatement (sb.tostring ())), for (int i=1;i<col.size (), i++) {for (Field Ff:fi) {if (Ff.getname (). Equals (Col.get (i))) {ff.setaccessible (true);p s.setobject (i, Ff.get (ob)); Fi[0].setaccessible (True);p S.setobject (Col.size (), Fi[0].get (OB)), int a = Ps.executeupdate (), if (a > 0) {//Get primary key, The primary key must be incremented, and there must be a method added to obtain the primary key rs = Ps.getgeneratedkeys (); if (Rs.next ()) {id = rs.getint (1);}}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS);} return ID;} public boolean update (Object ob) {Boolean b = false; Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; Class cl = Ob.getclass (); Field[] fi = Cl.getdeclaredfields (); Arraylist<string >col = Getallcolumn (Cl.getsimplename ()); StrIngbuffer sb = new StringBuffer (), Sb.append ("Update"), Sb.append (Cl.getsimplename ()); Sb.append ("set"); for (int i=1;i <col.size (); i++) {Sb.append (Col.get (i)); Sb.append ("?"); if (i! = Col.size ()-1) {Sb.append (",");}} Sb.append ("where"); Sb.append (Col.get (0)); Sb.append ("=?"); try {PS = conn.preparestatement (sb.tostring ())), for (int i=1;i<col.size (), i++) {for (Field Ff:fi) {if (Ff.getname (). Equals (Col.get (i))) {ff.setaccessible (true);p s.setobject (i, Ff.get (ob)); Fi[0].setaccessible (True);p S.setobject (Col.size (), Fi[0].get (OB)), int a = Ps.executeupdate (), if (a > 0) {b = true;}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS);} return b;} /** * * @param cl * @param the name database is listed in * @param value * @return */public ArrayList getlistbylike (Class cl,string Name,ob Ject value) {ArrayList ar = new ArrayList (); Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; ResultSet rs = null; Field[] fi = Cl.getdeclaredfields (); arraylist&Lt string> col = getallcolumns (Cl.getname ()); StringBuffer sb = new StringBuffer (), Sb.append ("select"), for (int i=0;i<col.size (); i++) {Sb.append (Col.get (i)); if ( I! = Col.size ()-1) {Sb.append (",");}} Sb.append ("from"), Sb.append (Cl.getsimplename ()), Sb.append ("where"); Sb.append (name); Sb.append ("Like '%"); Sb.append (value); Sb.append ("%");//like statement does not support placeholder try {PS = conn.preparestatement (sb.tostring ()); rs = Ps.executequery ( ), while (Rs.next ()) {Object obj = cl.newinstance (), for (String Str:col) {for (Field Ff:fi) {if (Str.equals (Ff.getname ())) {ff.setaccessible (true); Ff.set (obj, Rs.getobject (Ff.getname ())); break;}}} Ar.add (obj);}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS, RS);} return ar;} /** * This method is used for all queries * Note: Try to ensure that the data in the linked table in addition to the primary foreign Key association, try not to use the duplicate table column name * @param the queried data into the entity class in that class * @param SQL query SQL statement * @param OBS All Conditions * @return */public ArrayList getlistbysqlx (Class cl,string sql,object[]obs) {Connection conn = Baseconnection.getconnection (); ArrayList AR = new ArrayList (); PreparedStatement PS = null; ResultSet rs = null; Field[] fi = Cl.getdeclaredfields (); arraylist<string> col = new arraylist<string> (); try {PS = conn.preparestatement (SQL);// Get the columns in the datasheet resultsetmetadata MetaData = Rs.getmetadata (); int column = Metadata.getcolumncount (); for (int i=1;i<=column ; i++) {String columnName = metadata.getcolumnname (i); Col.add (columnName);} for (int i=0;i<obs.length;i++) {ps.setobject (i+1, obs[i]);} rs = Ps.executequery (), while (Rs.next ()) {Object OB = Cl.newinstance (), for (String Str:col) {for (Field Ff:fi) {if (Str.eq Uals (Ff.getname ())) {ff.setaccessible (true); Ff.set (ob, Rs.getobject (Ff.getname ())); Ar.add (OB);}} catch (Exception e) {//Todo:handle exception}finally{baseconnection.close (conn, PS, RS);} return ar;} Public ArrayList getlistbysome (Class cl,string name,object value) {ArrayList ar = new ArrayList (); Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; ResultSet rs = null; Field[] fi = CL. Getdeclaredfields ();//Get all the columns in the table arraylist<string> col = getallcolumns (Cl.getsimplename ()); StringBuffer sb = new StringBuffer (), Sb.append ("select"), for (int i=0;i<col.size (); i++) {Sb.append (Col.get (i)); if ( I! = Col.size ()-1) {Sb.append (",");}} Sb.append ("from"); Sb.append (Cl.getsimplename ()); Sb.append ("where"); Sb.append (name); Sb.append ("=?"); try {PS = conn.preparestatement (sb.tostring ());p s.setobject (1, value); rs = Ps.executequery (); while (Rs.next ()) {Object obj = Cl.newinstance (); for (String Str:col) {for (Field Ff:fi) {if (Str.equals (Ff.getname ())) {ff.setaccessible (true); Ff.set (obj, Rs.getobject (Ff.getname ())); Ar.add (obj);}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS, RS);} return ar;} Public Object Getobbyid (Class cl,int ID) {Object OB = NULL; Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; ResultSet rs = null; Field[] fi = Cl.getdeclaredfields ();//Get all the columns in the table arraylist<string> col = GetallcolUmns (Cl.getsimplename ()); StringBuffer sb = new StringBuffer (), Sb.append ("select"), for (int i=0;i<col.size (); i++) {Sb.append (Col.get (i)); if ( I! = Col.size ()-1) {Sb.append (",");}} Sb.append ("from"); Sb.append (Cl.getsimplename ()); Sb.append ("where"); Sb.append (Col.get (0)); Sb.append ("?"); try {PS = conn.preparestatement (sb.tostring ());p S.setint (1, id); rs = Ps.executequery (); while (Rs.next ()) {Object obj = cl . newinstance (); for (String Str:col) {for (Field Ff:fi) {if (Str.equals (Ff.getname ())) {ff.setaccessible (true); Ff.set ( obj, Rs.getobject (Ff.getname ())); break;}}}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS, RS);} return OB;} Public ArrayList getList (Class cl) {ArrayList ar = new ArrayList (); Connection conn = Baseconnection.getconnection (); PreparedStatement PS = null; ResultSet rs = null; Field[] fi = Cl.getdeclaredfields ();//Get all the columns in the table arraylist<string> col = getallcolumns (Cl.getsimplename ()); StringBuffer sb = new StringBuffer (); Sb.append ("Select"); for (int i=0;i<col.size (); i++) {Sb.append (Col.get (i)), if (I! = Col.size ()-1) {Sb.append (", ");}} Sb.append ("from"); Sb.append (Cl.getsimplename ()); try {PS = conn.preparestatement (sb.tostring ()); rs = Ps.executequery  (); while (Rs.next ()) {Object obj = cl.newinstance (), for (String Str:col) {for Field Ff:fi) {if (Str.equals (Ff.getname ())) {ff.setaccessible (true); Ff.set (obj, Rs.getobject (Ff.getname ())); break;}}} Ar.add (obj);}} catch (Exception e) {//Todo:handle exception}finally {baseconnection.close (conn, PS, RS);} return ar;} public static void Main (string[] args) {}}

  

Generic DAO method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.