Hibernate principle Simple implementation contrast JDBC

Source: Internet
Author: User

as one of the implementations of the ORM model, Hibernate is the bridge between the Java object model and the relational model, mainly through JDBC


To operate the database, providing a relatively comprehensive set of automated API . A simple simulation of hibernate 's


operating principle, in fact, the main or JDBC of Use, Or just take a look at this little example .

Package Com.tgb.cfl.hibernate;import Java.lang.reflect.method;import Java.sql.connection;import Java.sql.drivermanager;import Java.sql.preparedstatement;import Java.sql.sqlexception;import Java.util.HashMap; Import Java.util.list;import java.util.map;/** * Analog hibernatesession interface * @author Chen Fanglin * * */public class Session {/          /Store Entity Properties private map<string, string > columns = new hashmap<string, string > ();             String array holds the collection of entity's Get methods set string methodnames[];           Initialize the entity class properties and the method collection public Session () {//Initialize the entity, there is no way to read the configuration file, a bit troublesome.            Columns.put ("name", "name");                   Columns.put ("Age", "age");          Methodnames = new String[columns.size ()];                            }/** * Save method, persisted Object * @param user */public void Save (person person) { Strcolumn represents a property column in a table in a database.            and connect it together.            String strcolumn = "";            int index=0;     For (String Key:columns.keySet ())       {Strcolumn +=key+ ",";                  String v = columns.get (key);                Gets the property of the Get method v = "Get" + character.touppercase (V.charat (0)) + v.substring (1);               Methodnames[index] = v;            index++;              } strcolumn = strcolumn.substring (0, Strcolumn.length ()-1);          Stitching parameter placeholders, i.e.: (?,?)            String strvalue = "";                    for (int i=0;i<columns.size (); i++) strvalue + = "?,";              Gets the string substring strvalue = strvalue.substring (0,strvalue.length ()-1);                   String sql = "INSERT into" + "person" + "(" + Strcolumn + ")" + "values (" + strvalue + ")";              SYSTEM.OUT.PRINTLN (SQL);            try {//Get connection Class.forName ("Com.mysql.jdbc.Driver");                            Connection con = drivermanager.getconnection ("Jdbc:mysql://localhost/test", "root", "123456"); Jdbcstate Object PreparEdstatement state = (preparedstatement) con.preparestatement (SQL); for (int i=0;i<methodnames.length;i++) {//Use reflection to get the object of each method = person                      . GetClass (). GetMethod (Methodnames[i]);                      Get his return type Class CLA = Method.getreturntype ();                    Sets each property value in the inserted database according to the return type.                        if (Cla.getname (). Equals ("java.lang.String")) {String returnvalue = (string) method.invoke (person);                    State.setstring (i+1, returnvalue); } else if (Cla.getname () equals ("int")) {Integer returnvalue = (integer) method.                        Invoke (person);                    State.setint (i+1, returnvalue);                }}//Perform update state.executeupdate ();                State.close ();              Con.close (); } catch (ClassNotfoundexception e) {e.printstacktrace ();            } catch (SQLException e) {e.printstacktrace ();            } catch (Exception e) {e.printstacktrace (); }} public static void Main (string[] args) {person p = new person ();p. Setage ("1");p. SetName ("S2" ); Session Session = new session (), try {Session.save (p);} catch (Exception e) {//TODO auto-generated catch Blocke.printstack Trace ();}}}


This example is mostly modeled Session The operation of an entity class in an interface is mainly divided into the following steps

1. Dynamic splicing of SQL statements

2. how to get the entity class properties by Reflection get***

3. Get a database connection

4. updating data with PreparedStatement objects

this is JDBC of the object, the steps are mainly divided into

a) from Connection gets the PreparedStatement object in the

b) using PreparedStatement object mates Get method to get the property value

5. Garbage collection (recycle connection, object close)

we'll look back through this example . Hibernate , Hibernate What have you done to us?

The first step: Dynamic splicing SQL How is the statement implemented? Hibernate has a configuration file called ***.hbm.xml, which is used to configure the relationship between the entity and the database. This is also hibernate agreed well, you write, and finally read the suffix of the file this is the first step.

The second step: using reflection to get the corresponding Get method This is the use of reflection to do the main or through JDK The inside of this

Java.util.reflect.method this class to do. is also based on the API of the jdk .

Step three: Get the database connection. Hibernate has such a configuration file called hibernate.properties configuration file, the internal configuration of the database connection dialect, database-driven, Database address, user name password, and so on.

For example:

is also Hibernate That 's the deal, okay? In your program in the specified folder has this file, I directly read the node data can be. But the above example is written in the code to be dead.

Fourth Step: this is JDBC of the PreparedStatement object that API

Fifth Step: the corresponding is JDK of the API .

Standard of Hibernate The steps are as follows:

1. Through the configuration (). Configure (); Read and parse the Hibernate.cfg.xml config file

2. Read Hibernate.cfg.xml // Read and parse mapping information

3. Through Config.buildsessionfactory ();//Create Sessionfactory

4.sessionfactory.opensession ();//Open Sesssion

5.session.begintransaction ();//Create Transaction Transation

6.persistent operate persistent operation

7.session.gettransaction (). commit ();//COMMIT Transaction

8. Close the session, S esstionfactory

again through this picture, we find that in fact Hibernate is in JDBC Add a layer above it. Reminds me of where I heard a word before, flexible configuration

What is it? Nothing but add a layer, quite a sense of joy, then a thought but a few reasons.


So looking back, in fact,hibernate is just in the jdbc package, simplifying our direct operation of JDBC

the process. In java ,jdbc is the most primitive of the most direct way, cannot say that this method is not good, because the present

Popular Ibatis also for entities to create different SQL statement to do so the direct original method is also having its benefits

, such as: flexible, high efficiency. In exchange,hibernate is encapsulated on The basis of jdbc and avoids the program apes

to write directly to the tedious SQL statements as well as transaction maintenance and cache control, open source is also an aspect.  

of course , the explanation for the hibernate principle here is just the tip of hibernate. Later, such as hibernate 's cache, tri-state, and the processing of entity associations, transactions need to be studied carefully.

Hibernate principle Simple implementation contrast 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.