Java Reflection Mechanism Application: Object relational Mapping (ORM) __java

Source: Internet
Author: User
Tags reflection reserved

People who have studied Java should not be unfamiliar with SSH, struts,spring,hibernate the mainstream development framework of these three major enterprises, is being used by more and more Java developers. But it takes a little more effort to know the implementation mechanisms at the bottom of these frameworks. The implementation of these frameworks is actually using a lot of Java reflection mechanism principles. And what is the reflection mechanism, in this article, I do not elaborate, in Google, Baidu a lot of this information.

Here, for example, I use the Java mechanism to implement a framework similar to the Hibernate ORM (object-relational Mapping) database access layer. To implement this object-based database operation, the problem we need to consider is:

1. How to build SQL statements to implement CRUD (create, read, update, delete) operations, that is, we usually talk about additions and deletions to check the operation

2. How to determine which attributes in an object need to be insert or update

3. How to match the object with the underlying database table

It is not a very difficult thing to achieve a simple ORM framework if you can figure out these problems.

Suppose, now we need to student this object to do database additions and deletions of the operation, the corresponding database table is t_student

1. First we define a student class:

/** * Copyright (c) 2008 Ivan Lau, www.dongua.com, www.pcschoolchina.com * All rights reserved/public class student{PR ivate int id; private String name; Private String gender; private float height; private float weight; private int age; Private String address; Private String phone; Private String Mobile; Private String description; ..... }

2. Define the Daoutil class that generates SQL statements

Generate SQL Statement Daoutil class public classes Daoutil {/** * eg. insert into student (Name,age) VALUES (?,?) * @param vo * @param paramva Lues * @return * @throws illegalargumentexception * @throws illegalaccessexception * @throws invocationtargetexception * * The public static String Getinsertsqlfromvo (Object vo, List paramvalues) throws IllegalArgumentException, Illegalaccessexception, InvocationTargetException {//Save the name of the field StringBuilder FieldNames = new StringBuilder ("("); Save the question mark "?" in the argument. StringBuilder fieldparams = new StringBuilder ("Values ("); Class type = Vo.getclass (); Gets all public methods in the modified object according to the type of object Vo method[] methods = Type.getmethods (); For (methods Method:methods) {String methodname = Method.getname ();///Get the get*** method to if (Methodname.startswith ("get") ;&! " GetId ". Equals (methodname) &&!" GetClass ". Equals (methodname)) {String fieldName = methodname.substring (3). toLowerCase ();//Call yourself by method, To get the property value of the specified fieldname in the object. Object fieldval = Method.invoke (VO, null); if (fieldval!= null) {FieldnamEs.append (FieldName + ","); Fieldparams.append ("?,"); Adds the attribute value in the object to the Paramvalues parameter list. Paramvalues.add (Fieldval); }} Fieldnames.deletecharat (Fieldnames.length ()-1); Fieldparams.deletecharat (Fieldparams.length ()-1); Returns a string similar to this: (Name,age) VALUES (?,?), at which point the paramvalues is initialized. Return Fieldnames.append (")" + fieldparams.tostring () + ")"). ToString (); } }

3. Define data Access Class Basedao

Basedao performs database operations based on objects, which is part of an ORM. Dbmanager.executesql This function please see my previous 14 floor post. public class Basedao {protected static String TableName = null; public void Create (Object o) throws Exception {Stringbuf Fer sql = new StringBuffer (""); List params = new ArrayList (); Sql.append ("INSERT into" + this.tablename); Sql.append (DAOUTIL.GETINSERTSQLFROMVO (o, params)); SYSTEM.OUT.PRINTLN ("sql:" + sql.tostring ()); try {dbmanager.executesql (sql.tostring (), params);} catch (Exception ex) {throw ex;}} }

4. Execution SQL statements for the ExecuteSQL defined in the Dbmanager class

public static void ExecuteSQL (String sql, List params) throws Exception {Connection con; PreparedStatement pstmt; con = null; pstmt = null; Boolean aborttransaction = false; int execute_rs =-1; try {con = dbmanager.gettransactionconnection (); pstmt = con.preparestatement (sql); int i = 0; for (Object Param:params) {param = param==null? "": param; Pstmt.setobject (i + 1, param); i++; } execute_rs = Pstmt.executeupdate (); catch (SQLException sqlex) {aborttransaction = true; throw Sqlex;} catch (Exception e) {aborttransaction = true; thro W e; finally {dbmanager.closetransactionconnection (con, aborttransaction);}}

5. Final writing of a test class

Test class public class Test {public static void main (string[] args) {Basedao dao = new Basedao (); Studentvo vo = new Studentvo (); Vo.setname ("Ivan"); Vo.setaddress ("Guangzhou Masters It"); Vo.setdescription ("I love wax gourd nets, love Java and Python"); try {dao.create (VO);} catch (Exception e) {e.printstacktrace ();}} }

All rights reserved: liuwan@pcschoolchina.com guangzhou Masters it http://www.pcschoolchina.com/

If you need complete source code, please leave your email, I will reply.

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.