Hibernate4.x and hibernate4.x

Source: Internet
Author: User

Hibernate4.x and hibernate4.x

Hibernate is an excellent persistence framework and ORM framework. It is often used in routine Java development. This article describes the basic knowledge of Hibernate4.x through a simple example.

Create a Java project and add the jar package and database driver package to be used by Hibernate,

The project structure after completion is roughly as follows:

  

 

Hibernate configuration file: hibernate. cfg. xml

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <! DOCTYPE hibernate-configuration PUBLIC 3 "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 

Persistence class: News. java

  

 1 package com.yl.hibernate.helloworld; 2  3 import java.sql.Date; 4  5 public class News { 6      7     private Integer id; 8     private String title; 9     private String author;10     11     private Date newsdate;12 13     public Integer getId() {14         return id;15     }16 17     public void setId(Integer id) {18         this.id = id;19     }20 21     public String getTitle() {22         return title;23     }24 25     public void setTitle(String title) {26         this.title = title;27     }28 29     public String getAuthor() {30         return author;31     }32 33     public void setAuthor(String author) {34         this.author = author;35     }36 37     public Date getNewsdate() {38         return newsdate;39     }40 41     public void setNewsdate(Date newsdate) {42         this.newsdate = newsdate;43     }44 45     public News(){}46     47     public News(String title, String author, Date newsdate) {48         super();49         this.title = title;50         this.author = author;51         this.newsdate = newsdate;52     }53 54     @Override55     public String toString() {56         return "News [id=" + id + ", title=" + title + ", author=" + author57                 + ", date=" + newsdate + "]";58     }59     60     61     62 }

Configuration file of persistence class: News. hbm. xml

1 <? Xml version = "1.0"?> 2 <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 <! -- Generated 2014-11-19 21:19:05 by Hibernate Tools 3.4.0.CR1 --> 5 

Test class: HibernateTest. java

1 package com. yl. hibernate. helloworld; 2 3 import java. SQL. date; 4 5 import org. hibernate. session; 6 import org. hibernate. sessionFactory; 7 import org. hibernate. transaction; 8 import org. hibernate. cfg. configuration; 9 import org. hibernate. service. serviceRegistry; 10 import org. hibernate. service. serviceRegistryBuilder; 11 import org. junit. test; 12 13 public class HibernateTest {14 15 @ Test16 public voi D test () {17 // 1. create a SessionFactory object 18 SessionFactory sessionFactory = null; 19 20 // 1.1 create a Configuration object, corresponding to the basic Configuration information of hibernate and object Association ing information 21 configuration Configuration = new Configuration (). configure (); 22 // creation method before 4.0 23 // sessionFactory = configuration. buildSessionFactory (); 24 25 // 1.2 create a ServiceRegistry object: the newly added object hibernate4.x. Any configuration and server of hibernate must be registered in this object before it can be valid 26 ServiceRegistry serviceRegistry = 27 new ServiceRegistryBuilder (). applySettings (configuration. getProperties () 28. buildServiceRegistry (); 29 30 // 1.3 create SessionFactory object 31 sessionFactory = configuration. buildSessionFactory (serviceRegistry); 32 33 // 2. create a Session object 34 Session session = sessionFactory. openSession (); 35 // 3. start Transaction 36 transaction Transaction = session. beginTransaction (); 37 // 4. execute the save operation 38 News news = new News ("Java", "yulei", new Date (new java. util. date (). getTime (); 39 session. save (news); 40 41/* News news2 = (News) session. get (News. class, 2); 42 System. out. println (news2); */43 // 5. commit transaction 44 transaction. commit (); 45 // 6. disable Session46 session. close (); 47 // 7. disable SessionFactory object 48 sessionFactory. close (); 49 50} 51 52}

---------------------------------------------------- The preceding code is partial --------------------------------------------------------------------------------------------

---------------------------------------------------- The following is an explanation of some codes --------------------------------------------------------------------------------------------

Configuratioin class
The Configuratioin class is responsible for managing the configuration information of Hibernate. Includes the following:
Underlying information of Hibernate running: Database URL, user name, password, JDBC Driver Class, database Dialect, database connection pool, etc. (corresponding to hibernate. cfg. xml) File
Mappings between persistence classes and database tables (*. hbm. xml file)
You can create a Configuration in either of the following ways:
Attribute file: Configuration cfg = new Configuration ();
XML file: Configuration cfg = new Configuration (). configuration ();
The Configuration method of configuration also supports access with parameters:
File file = new File ("simple. xml ");
Configuration cfg = new Configuration (). configuration (file );

SessionFactory Interface
The compiled memory image for a single database ing is thread-safe.
Once the SessionFactory object is built, it is assigned specific configuration information.
SessionFactory is the factory that generates sessions.
Constructing SessionFactory consumes a lot of resources. Generally, only one SessionFactory object is initialized in the next application.
Hibernate4 adds a ServiceRegistry interface. All Hibernate-based configurations or services must be registered with this ServiceRegistry for the Service to take effect.
To create a SessionFactory in Hibernate4:
    

1 // 1.1 create a Configuration object, corresponding to the basic Configuration information of hibernate and object Association ing information 2 configuration Configuration = new Configuration (). configure (); 3 4 // 1.2 create a ServiceRegistry object: the newly added object hibernate4.x. Any configuration and server of hibernate must be registered in this object before it can be valid. 5 ServiceRegistry serviceRegistry = 6 new ServiceRegistryBuilder (). applySettings (configuration. getProperties () 7. buildServiceRegistry (); 8 9 // 1.3 create SessionFactory object 10 sessionFactory = configuration. buildSessionFactory (serviceRegistry );

 

Session Interface
Session is a single-threaded object for interaction between applications and databases. It is the center of Hibernate operation. All persistence objects must be managed by sessions before they can be persisted. The lifecycle of this object is short. The Session object has a level-1 cache, indicating that data of all persistent layer operations is cached at the session object before being flushed. It is equivalent to the Connection in JDBC.
After the persistence class is associated with the Session, it becomes persistent.
  

Session method:
Methods for obtaining persistent objects: get (), load ()
Persistence Object Storage, update, and deletion: save (), update (), saveOrUpdate (), delete ()
Start transaction: beiginTransaction ()
Session management methods: isOpend (), flush (), clear (), evict (), close (), etc.

Transaction)
Represents an atomic operation. It has the concept of database transactions. All persistence layers should be performed under transaction management, even read-only operations.
Transaction tx = session. beginTransaction ();
Common Methods:
Commit (): Submit the associated session instance
Rollback (): cancels a transaction.
WasCommitted (): checks whether the transaction is committed.

Two configuration items in the Hibernate configuration file
Hbm2ddl. auto: This attribute helps programmers implement forward engineering, that is, the Java code generates database scripts and then generates specific table structures. Value: create | update | create-drop | validate
Create: the database table is generated based on the. hbm. xml file. However, the last table is deleted and re-generated every time the database is run.
Create-drop: The table is generated based on the. hbm. xml file. However, when SessionFactory is disabled, the table is automatically deleted.
Update: The most commonly used attribute value. hbm. xml file to generate database tables. hbm. the structure of the table corresponding to the xml file and the database is different. Hibernate updates the structure of the data table, but does not Delete the existing rows and columns.
Validate: it is compared with the table in the database. If the column in The. hbm. xml file does not exist in the data table, an exception is thrown.
  

Format_ SQL: whether to convert SQL statements into well-formatted SQL statements. Value: true | false

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.