Java encapsulation of the DAO layer through JDBC

Source: Internet
Author: User

Objective

In front of a section, I specifically explained that Java through the JDBC database operation of MySQL, which mainly explains the MySQL database connection and simple operation, but in the real Java project, we have to constantly deal with the database, In order to improve the efficiency of database operation and increase the reusability of the Code, a DAO layer is repackaged, namely the data access layer, which is used to access the database to persist the data.

DAO layer Design DAO Layer Operations Common steps:
    • 1. Write SQL statements
    • 2. Get the connection
    • 3. Create stmt
    • 4. Execute SQL

A) update
String sql = "Delete from admin where id=?";
String sql = "INSERT into admin (username,pwd) VALUES (?,?)"
public void Update (String sql, object[] paramvalues);

b) Enquiry
String sql = "SELECT * from admin";
String sql = "SELECT * from admin where id=?" and pwd =? ";
What type of object is passed in to encapsulate why type
Requirement: The name of the column to be the same as the property name of the object of the specified type
Public List query (String sql, object[] paramvalues, Class clazz);
T T; Assigning values to Objects

    • 5. Close/Abnormal
Write Basedao, all of the DAO that you write to inherit this class

Where the Jdbcutil class in the previous blog Java through the JDBC database operation of the MySQL is described in detail, here is more than said.

/** * General DAO, all the DAO written by himself inherit this class; * This class defines 2 common methods: * 1. Update * 2. Query@author Charlie.chen * * * *PublicClassBasedao {Initialize parametersPrivate Connection con;Private PreparedStatement pstmt;Private ResultSet RS;/** * General method of Query *@param SQL *@param paramsvalue * *Public <T> list<t>Query (String SQL, object[] paramsvalue,class<t> clazz) {try {Returns the collection list<t> List =New Arraylist<t> ();Object T T =Null1. Get Connection con = jdbcutil.getconnection ();2. Create stmt Object pstmt = con.preparestatement (sql);3. Gets the number of placeholder parameters and sets the value of each parameterint count = Pstmt.getparametermetadata (). GetParameterCount ();if (paramsvalue! =Null && paramsvalue.length >0) {for (int i=0; i<paramsvalue.length; i++) {Pstmt.setobject (i+1, paramsvalue[i]); } }4. Execute Query rs = pstmt.executequery ();5. Get result set meta data resultsetmetadata RSMD = Rs.getmetadata ();---> Get the number of columnsint columnCount = Rsmd.getcolumncount ();6. Traverse RSwhile (Rs.next ()) {The object to encapsulate T = clazz.newinstance ();7. Iterate through each column of each row, encapsulating the datafor (int i=0; i<columncount; i++) {Gets the column name for each column String columnName = rsmd.getcolumnname (i +1);Gets the column name of each column, corresponding to the value of Object value = Rs.getobject (ColumnName);Encapsulation: Set to the properties of the T object "Beanutils component" Beanutils.copyproperty (t, columnName, value); }Adds the encapsulated object to the list collection List.add (t); }return list; }catch (Exception e) {ThrowNew RuntimeException (e); }finally {Jdbcutil.closeall (con, pstmt, RS);}}/** * General method of updating *SQL statement for @param SQL update (update/insert/delete) *@param the value corresponding to the placeholder in the Paramsvalue SQL statement (if there is no placeholder, pass in null) */PublicvoidUpdate (String sql,object[] paramsvalue) {try {Get Connection con = jdbcutil.getconnection ();Creates a stmt object that executes the command pstmt = con.preparestatement (sql);//Parameter meta-data: Gets the number of placeholder arguments int count = Pstmt.getparametermetadata (). GetParameterCount (); //Set the value of the placeholder parameter if (paramsvalue! = null && paramsvalue.length > 0) { //loop to parameter assignment for (in T i=0;i<count;i++) {pstmt.setobject (i+1, paramsvalue[i]);}} //Perform update pstmt.executeupdate ();} catch (Exception e) { throw new RuntimeException (e);} finally {Jdbcutil.closeall (con, pstmt, null);}}           

The DAO class that writes the actual operation inherits from Basedao
PublicClassAdmindaoExtendsBasedao {DeletePublicvoidDeleteint id) {String sql ="Delete from admin where id=?"; Object[] Paramsvalue = {ID};Super.update (SQL, paramsvalue); }InsertPublicvoidInsert (admin admin) {String sql ="INSERT into admin (username,pwd) VALUES (?,?)"; Object[] Paramsvalue = {admin.getusername (), Admin.getpwd ()};Super.update (SQL, paramsvalue); }Search Allpublic list<admin> getall () {String sql = " SELECT * from admin "; list<admin> list = super.query (sql, null, Admin.class); return list;} //based on conditional query (primary key) public Admin findById (int ID) {String sql =  "select * from admin where id=?"; list<admin> list = super.query (sql, new Object[]{id}, Admin.class); return (List!=null&&list.size () >0)? List.get (0): null;}       

JavaBean class
/** * 1. Bean Class Design *@author Charlie.chen * * * *PublicClassAdmin {Privateint id;Private String UserName;Private String pwd;Privateint age;Private Date birth;Public DateGetbirth () {return birth; }PublicvoidSetbirth (Date birth) {This.birth = birth; }PublicIntGetage () {return age; }PublicvoidSetage (int age) {This.age = age; }Public StringGetpwd () {return pwd; }PublicvoidSetPwd (String pwd) {This.pwd = pwd; }PublicIntGetId () {return ID; }Publicvoidsetid (int ID) {this.id = ID;} public String getusername () {return UserName; } public void setUserName (String UserName) {this.username = UserName;}  @Override public String  ToString () {return  "Admin [age=" + Age +     

Java encapsulation of the DAO layer through JDBC

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.