Java's hibernate framework combines MySQL's Introductory learning tutorial _java

Source: Internet
Author: User
Tags rollback

0. About Hibernate
Hibernate is the meaning of hibernation, it refers to the hibernation of animals, but the hibernate discussed in this paper is not related to hibernation, but the next to discuss the SSH2 framework of a member. Hibernate is an Open-source project that is a framework for an object relational model and a very lightweight encapsulation of JDBC, which programmers can develop with object programming thinking.
Download Address: http://hibernate.org/orm/downloads/
Note: Lightweight and heavyweight difference, lightweight frame package smaller, and simpler to use, and easy to test, development efficiency; The heavyweight framework is large, the internal encapsulation business process is complex, and testing is difficult, such as struts.

Object Relational Model:

Hibernate implements the mapping of object-relational model, in programming, programmers can directly use object model to operate the database, it has a lightweight encapsulation of JDBC, and also encapsulates SQL statements for database operations, and is simple to use. Although it has a lot of advantages, but the use of database characteristics of the statement, it will be difficult to tune, such as: stored procedures, etc. is more difficult.
Hibernate Advantages and Disadvantages:
(1) Advantages
A, increase productivity;
B, the development of more targeted (impedance mismatch);
C, portability;
D, no intrusion, support for transparent persistence.
(2) Disadvantages
A, the use of database characteristics of the statement, it will be difficult to tune;
B, there are problems in the updating of mass data;
C, the system has a large number of statistical query function.


Second, hibernate instance
The above has done some preliminary reading to Hibernate, has the theory certainly to have the practice, has not used the hibernate is does not understand its convenience, This is just like a person who likes to drink the first time to taste Maotai, the use of a more profound understanding.
The following example uses a MySQL database, creates a database named Hibernate_first in MySQL, and creates a user table with the Hibernate mapping file and adds information to the user table.
Concrete Steps:
(1) Create a normal Java application
(2) Add hibernate jar package, you need to add a jar package Hibernate.jar, The Third-party jar package referenced by Hibernate and the hibernate and MySQL-connected jar bundle are introduced together, and the
(3) Adds the database connection profile Hibernate.cfg.xml.

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibernate.sour Ceforge.net/hibernate-configuration-3.0.dtd ">  

(4) Establish entity class name as User.java

Package com.hibernate; 
 
Import java.util.Date; 
 
public class User { 
  private String ID; 
  Public String GetId () {return 
    ID; 
  } 
  public void SetId (String id) { 
    this.id = ID; 
  } 
  Public String GetName () {return 
    name; 
  } 
  public void SetName (String name) { 
    this.name = name; 
  } 
  Public String GetPassword () {return 
    password; 
  } 
  public void SetPassword (String password) { 
    this.password = password; 
  } 
  Public Date Getcreatetime () {return 
    createtime; 
  } 
  public void Setcreatetime (Date createtime) { 
    this.createtime = createtime; 
  } 
  Public Date Getexpiretime () {return 
    expiretime; 
  } 
  public void Setexpiretime (Date expiretime) { 
    this.expiretime = expiretime; 
  } 
  private String name; 
  private String password; 
  Private Date createtime; 
  Private Date expiretime; 
} 

(5) Create a mapping file User.hbm.xml for the user entity class, complete the mapping of the entity class, and add the file to the Hibernate.cfg.xml file.

<?xml version= "1.0"?> 
<! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" 
"http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "> 
<!--generated 2014-4-30 15:39:33 by hibernate Tools 3.4.0.cr1--> 
< hibernate-mapping> 
  <class name= "Com.hibernate.User" > 
    <id name= "id" > 
      <generator class= "uuid"/> 
    </id> 
    <property name= "name"/> <property name= 
    "password"/> 
    <property name= "Createtime"/> 
    <property name= "Expiretime"/> 
  </class> 
</ Hibernate-mapping> 

(6) Write Exportdb.java to convert the mapping file into the corresponding DDL.

Package com.hibernate; 
 
Import org.hibernate.cfg.Configuration; 
Import Org.hibernate.tool.hbm2ddl.SchemaExport; 
public class Exportdb {public 
  static void Main (string[] args) { 
    //Declare first get profile 
    //default read Hibernate.cfg.xml file 
    Configuration cfg=new Configuration (). Configure ();  
     
    Exports the read XML file to the DDL 
    schemaexport export=new schemaexport (CFG); 
    Export.create (True, true); 
  } 
 

Run the Exportdb class to complete the creation of the database table, in CMD view after the specific operation of the following view:

The above example only completes the connection database and creates the table in the database the operation, after creates the table to add the data to the table, establishes the client class clients, adds the new user information to the user table, the concrete code as follows:

Package com.hibernate; 
 
Import Java.util.Date; 
Import org.hibernate.Session; 
Import Org.hibernate.SessionFactory; 
 
Import org.hibernate.cfg.Configuration; public class Client {public static void main (string[] args) {//Read Hibernate.cfg.xml file Configuration cfg 
     
    =new Configuration (). Configure (); 
    Create a sessionfactory, which is equivalent to database mirroring, sessionfactory because it is mirrored so just one, it is best to create once//usually thread safe. 
     
    Sessionfactory factory=cfg.buildsessionfactory (); 
     
    Take the session session Session=null; 
      try{session=factory.opensession (); 
      Open transaction session.begintransaction (); 
      User User=new user (); 
      User.setname ("John"); 
      User.setpassword ("123"); 
       
      User.setcreatetime (New Date ()); 
       
      Save the User Object Session.save (user); 
    Commits a transaction session.gettransaction (). commit (); 
    }catch (Exception e) {e.printstacktrace ()//Print error message/ROLLBACK TRANSACTION session.gettransaction (). rollback (); 
   }finally{   if (session!= null) {if (Session.isopen ()) {//close session session.close (); 
 } 
      } 
    } 
  } 
}

Viewing the added information in MySQL shows the following figure:

The information above is already written to the database. The data in the database generates the corresponding rows in the database after save, but there is no real save at this time, but there is already a corresponding row of data in the database, and the data is submitted to the database after the transaction commit is completed using session.

Related Article

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.