Hibernate's simulated Hibernate persistence operation

Source: Internet
Author: User


Hibernate persistent operation in simulated hibernate


have used Hibernate, we all know, because of its object-oriented design, it is very convenient to use, and has a good cross-database, then the bottom of hibernate is how to achieve it? In fact, it is the transformation of the object model into a relational model, and ultimately the SQL statement to execute.

have seen Hibernate Source students should find that the core of Hibernate bottom is Proxy and reflection , then so we can understand why Hibernate is used is always deadly in efficiency.

Ok, here is a simple simulation of the Hibernate-orm Save () method , to glimpse, a little bit about Hibernate 's underlying implementation. Here I mainly demonstrate how Hibernate uses reflection to get data, types, etc., to be mentioned here, the vast number of Java practitioners, want to break through the Java technology path,Java Reflection mechanism, which must be mastered.

start by simulating a new Session entity class, simulating a save () method

for convenience, I do not write the configuration file, if you want to write, you can refer to Hibernate 's


Configuration cfg=new configuration (); Cfg.configure (); Sessionfactory=cfg.buildsessionfactory ();

will be Hiberane the source code in, see for yourself how it is implemented using DOM4J resolution.


First create an entity class:

Package csg.hibernate.entity;/** * * @author caesar.hu * @Date2014 -11-28 * @Time Morning 09:32:08 * @TODO */public class Student {Private Integer id;private String name;private integer age;public integer getId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Integer Getage () {return age;} public void Setage (Integer age) {this.age = age;}}


Look at the code: Then we simulate a session class, which constructs a save () method,

Package csg.hibernate.entity;import java.lang.reflect.method;import java.sql.connection;import  java.sql.DriverManager;import java.sql.PreparedStatement;import java.util.HashMap;import  java.util.map;/** *  *  @author  Caesar.hu *  @Date  2014-11-27 *   @Time   Afternoon 06:02:05 *  @TODO simulate a session */public class session {// 1 , write a table name, this table name, should theoretically be read in Student.hbm.xml, or annotated JPA map//  I write directly here, meaning that the data stored in the database table corresponds to this string tablename  =  "_student";// 2, why create a string-type map?   This map stores the entity's Field properties and database field matches, and is itself configured in the file map<string, string> cfs = new  Hashmap<string, string> (); String[] methodnames;// new an empty collection is primarily convenient for reflection using Public session ()  {cfs.put ("_id",  "id"); Cfs.put ("_name",  "name"), Cfs.put ("_age",  "Age"); Methodnames = new string[cfs.size ()];} Public void save (student s) &NBSP;THROWS&NBSP;EXCEPTION&NBSP;{//&NBSP;3, create SQL Statement string sql = createsql (); string url =  "Jdbc:mysql://localhost/hibernate"; string username =  "Root"; string password =  "Root"; Class.forName ("Com.mysql.jdbc.Driver"); Connection conn = drivermanager.getconnection (Url, username, password); Preparedstatement ps = conn.preparestatement (SQL);// 9,sql write well, here is not the need to set?   Similar ps.setname (1,s.getid);// ps.setinterge (2,s.getage)//How to set? How do you know what kind of transmission comes in? So the most important thing here is to use the reflection type for  (int i = 0; i < methodnames.length; i++)   {System.out.println (methodnames[i]);//  first takes the GETAGE&NBSP;GETINT//10,  , which is stored in the data A series of methods Getage,getname,getid and return type Integer,string,integermethod m = s.getclass () are reflected by the reflection mechanism based on the method of the entity. GetMethod (Methodnames[i]); System.out.println (m); System.out.println (S.getclass ()  +  "-------"  + m +  "---------" + m. GetName ()  +  "-----"  + m.getreturntype ());//11, gets the return type of the getage,getint,getname  in the array class  r = m.getreturntype ();//12, depending on the return type, whether it should be ps.setstring, or ps.setintegerif  (R.getname (). Equals ( "Java.lang.String") &NBSP;{//13, Invoke is a method within the reflection, whose function is to reflect the property value by the return value type of the class//14, Getage.invoke (s); It is also possible to reflect the return type string returnvalue =  (String)  m.invoke (s) by value; System.out.println (returnvalue);p s.setstring (i + 1, returnvalue);} 15, also if the judgment is an Integer type, ps.setintegerif  (R.getname (). Equals ("Java.lang.Integer"))  {system.out.println (M.invoke (s));integer returnvalue =  (Integer)  m.invoke (s);// system.out.println ( returnvalue);p s.setint (I + 1, returnvalue);}}  ps.executeupdate ();p s.close (); Conn.close ();} Private string createsql ()  {String str1 =  ""; int index = 0;for   (String s : cfs.keyset ())  {// 4, using key from map to get valuestring v  = cfs.get (s);// 5, according to the Get,set method we can know that the first letter of the field needs to be capitalized,// 6, this code is to take out the value of the first letter capital plus getv =  Character.touppercase (V.charat (0))  + v.substring (1);// 7, so that the new empty collection is placed on the Getid,getname, getagemethodnames[index] =  "Get"  + v;str1 += s +  ","; index++;} Str1 = str1.substring (0, str1.length ()  - 1); string str2 =  "";for  (Int i = 0; i < cfs.size ();  i++ )  {str2 +=  "?,";} Str2 = str2.substring (0, str2.length ()  - 1); string sql =  "insert into "  + tableName +  "("  + str1  +  ")  +  values (" + str2 +  ")"// 8, this section Sql==// insert into  _table (Id,name,age) values (?,?,?); Return sql;}}


Final Test code:


Package Junittest;import csg.hibernate.entity.session;import csg.hibernate.entity.student;/** * * @author Caesar.hu * @ DATE2014-11-28 * @Time am 09:32:15 * @TODO */public class Test {public static void main (string[] args) throws Exception{stud ENT student=new student (); Session S=new session (); Student.setid (1); Student.setage (n); Student.setname ("Zhang San"); S.save (student);}}


ok here, you should be able to understand why Hibernate web performance issues on why Hibernate reflection mechanism for java< Span style= "font-family: ' The song Body '; > How important is

actually Hibernate 's source code is the same, but it is in the bottom of a large number of packages, and in order to performance Hibernate also has the direct data generation binary stream operation. for the configuration file you can see Hibernate Source code is how to use dom4j parsing Hibernate.cfg.xml This file, written especially classic, Ok?

Java practitioners, want to breakthrough in technology, reflection mechanism must be mastered!





This article from "Promise always attached to the small wood 、、、" blog, please be sure to keep this source http://1936625305.blog.51cto.com/6410597/1583938

Hibernate's simulated Hibernate persistence operation

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.