Implementation of Java JDBC Universal DAO

Source: Internet
Author: User

When the database and entity classes are well designed, how many DAO does it take to have several entity classes? Obviously not.

Using the reflection mechanism of Java, a DAO can implement the operation of all entity classes.

The idea is to pass over an entity class, use the entity class to get the table, take each field of the entity class out and put it in the corresponding field of the table ....

However, if the Entity class field changes, inserting data into the database at this time will be an error because there is no field in the table corresponding to the entity class attribute.

We're going to use the reflection mechanism of Java at this time.

We first need to get all the fields of the table, and then get all the attributes of the entity class, two each, the entity class has a property and the database does not correspond to the field, it is the basic idea

The code is as follows:

 Package Com.lp.dao;import Java.lang.reflect.field;import Java.sql.connection;import java.sql.PreparedStatement; Import Java.sql.resultset;import java.sql.resultsetmetadata;import Java.sql.sqlexception;import java.sql.Statement Import java.util.arraylist;import java.util.list;import com.lp.bean.goods;/*** 2015.7.20 using Java Reflection to implement Universal DAO Even if the Entity class field changes in the bean layer can be changed or deleted. * * @author Lp*/public class Daopro {//By database name all columns in the database public list<string> getcolumns (St Ring tableName) {Connection Connection = Dbhelper.getcon (); Statement Statement = Dbhelper.getstatement (); ResultSet ResultSet = null; list<string> list = new arraylist<string> (); try {String sql = "SELECT * from" + TableName + "where 1=2"; resu Ltset = Dbhelper.getstatement (). executeQuery (SQL); ResultSetMetaData data = Resultset.getmetadata (), int columnscount = Data.getcolumncount (); for (int i = 1; I <= COLUMNSC Ount; i++) {String s = data.getcolumnname (i); List.add (s);}} catch (SQLException e) {e.printstacktrace ();} finally {DbhelPer.clores (connection, statement, ResultSet);} return list;} Populates the entity class, returning an entity class Collection public List GetList (class cl) {int i = 0; List Objs = new ArrayList (); Connection Connection = Dbhelper.getcon (); Statement Statement = Dbhelper.getstatement (); ResultSet ResultSet = null; field[] fields = Cl.getdeclaredfields (); list<string> columnsname = GetColumns (Cl.getsimplename ()); String sql = "SELECT * from" + cl.getsimplename (); try {System.out.println (sql); resultSet = statement.executequery (sql); System.out.println (i++), while (Resultset.next ()) {System.out.println (i++), Object obj = Cl.newinstance (); for (String Str:columnsname) {for (Field ff:fields) {if (Str.equals (Ff.getname ())) {ff.setaccessible (true); Ff.set (obj, ResultSet. GetObject (Ff.getname ())); break;}}} Objs.add (obj);}} catch (SQLException e) {e.printstacktrace ();} catch (IllegalArgumentException e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace ();} catch (Instantiationexception e) {e.printstacktrace ();} return OBJS;}public void AddData (Object object) {Connection Connection = Dbhelper.getcon (); ResultSet ResultSet = null; PreparedStatement preparedstatement = null; String tableName = Object.getclass (). Getsimplename (); field[] fields = Object.getclass (). Getdeclaredfields (); list<string> allcolumns = GetColumns (tableName); StringBuffer buffer = new StringBuffer (); StringBuffer buffer1 = new StringBuffer () buffer.append ("INSERT into"); Buffer.append (tableName); Buffer.append ("("); for (int i = 1; i < allcolumns.size (); i++) {Buffer.append (Allcolumns.get (i)); Buffer1.append ("?"); if (i! = Allcolumns.size ()-1) {Buffer.append (","); Buffer1.append (",");}} Buffer.append (") VALUES ("); Buffer.append (Buffer1); Buffer.append (")");//System.out.println (buffer.tostring ()); try {preparedstatement = Connection.preparestatement (buffer.tostring ()); for (int i = 1; i < allcolumns.size (); i++) {fo R (Int j = 0; J < Fields.length; J + +) {if (Fields[j].getname ()). Equals (Allcolumns.get (i))) {fields[j].setaccessible (t Rue); if (Fields[j].get (object) = = null) {Preparedstatement.setobject (I, "this field has no padding");} else {preparedstatement.setobject (i , Fields[j].get (object));} Break;}}} int a = Preparedstatement.executeupdate (); System.out.println (a);} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IllegalArgumentException e) {//TOD O auto-generated catch Blocke.printstacktrace ();} catch (Illegalaccessexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {dbhelper.clores ( Connection, PreparedStatement, ResultSet);}} public static void Main (string[] args) {goods c = new Goods (); new Daopro (). AddData (c);}}

  

Implementation of Java JDBC Universal DAO

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.