The basic mapping usage in Java's hibernate framework is explained _java

Source: Internet
Author: User
Tags generator uuid

Hibernate classification and integration found that in fact, hibernate is divided into three major parts: core objects, mapping, HQL, the most commonly used in the development process, the first several discussed the core objects and the transformation between objects, and then discuss the hibernate mapping using methods.

An important function of hibernate is mapping, which can be transformed between the object model and the relational model, which is advocated by object-oriented programming, where developers only need to be concerned with coding in the object model. Mappings between objects and relational databases are usually defined by XML documents. This mapping document is designed to be readable and can be modified manually. This mapping relationship is summed up in the following illustration:

Mappings are defined through XML, managed using a session created by Hibernate, and finally submitted by session to the database using JTA. The session can be understood as the persistence Manager, which manages the objects in the persistence layer, which is created by Sessionfactory. When using Hibernate programming, you first have to connect to the database, so you first need to look at the configuration of the database connection in the XML, create sessionfactory based on the configuration of the document (which can be understood as database mirroring), and then create a session by Sessionfactory. Finally, by session unification, the changes are committed to the database, which completes all of the operations.


Use Process
1. Create the mapping file, the mapping file with the. hbm.xml suffix name, indicating that it is a hibernate mapping file;
2. Register the entity class in the mapping file and add the attributes of the entity class to the mapping class, and when adding the attribute, specify that both values are IDs and property,id indicate that it is the unique identifier of an entity, which indicates that it is a field column of the table;
3. Submit the changes and synchronize the data.
Note: Developers who have developed XML data to go to a database will soon be able to understand that this mapping is actually a batch update, batch creation process, mapping is no exception, hibernate set a set of mapping standards, in accordance with the standard can be implemented, its internal implementation is still dead, So it's just relatively flexible and easy to use.

A simple entity class mapping process:
1. Entity class User1 Property Code:

 package com.hibernate; 
 
Import Java.util.Date; 
 public class User1 {private String ID; 
 private String name; 
 private String password; 
 Private Date Createtime; 
 Private Date Expiretime; 
 Public String GetId () {return 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; 
 The public void Setcreatetime (Date createtime) {this.createtime = Createtime; 
 Public Date Getexpiretime () {return expiretime; 
 The public void Setexpiretime (Date expiretime) {this.expiretime = Expiretime; } 
  
} 


2. User1.java's mapping file User1.hbm.xml internal code implementation:
A method that can be set in the underlying database in Hibernate also provides a way to set up specific mapping relationships using tag properties.
Class tags are used in--> tables, commonly used properties:
(1) Name: Maps an entity class whose value needs to be set to the name of the entity class that needs to be converted into a table, and the corresponding entity class is found according to the attribute when synchronizing.
(2) Table: Map the name of a database table, use this property to specify a mapped table if the table you want to map is not the same name as the entity class, and create a table based on that property value if it does not exist.
View the table structure generated by the configuration in the previous illustration, as shown in the following figure:

The table name changes in the T_user1;id field is renamed to user_id, the field length is 32 bits, the Createtime property is mapped to the database field Create_time, and is modified to the date type.
Property--> fields use ID or property labels, commonly used properties:
(1) Name: The function is similar to the name of the class label, which values the mapping attribute name of the entity class;
(2) Column: A table similar to the class label for the entity class that specifies the column name of the mapping table, if it does not exist, will be created;
(3) Type: Specifies the data type that maps to a field in the database, and view the document as needed;
(4) generator, which is optional and is used to generate a unique identity for a persistent class.

<id name= "id" type= "long" column= "cat_id" > 
  <generator class= "Org.hibernate.id.TableHiLoGenerator" > 
    <param name= "table" >uid_table</param> 
    <param name= "column" >next_hi_value_column</ param> 
  </generator> 
</id> 


All generators implement the Org.hibernate.id.IdentifierGenerator interface. This is a very simple interface, and some applications can choose to provide their own specific implementations. Of course, Hibernate offers a lot of built-in implementations. The following are some of the most commonly used:
(1) Identity: The identifier returned is a long, short, or int type. A self-added field similar to a database.
(2) Sequence: Use a sequence (sequence) in Db2,postgresql, Oracle, SAP DB, Mckoi, and use a generator (InterBase) in generator. The identifier returned is a long, short, or int type. Growing in the entire database, rather than in a single table, requires adding attributes to the individual tables in addition to the need to add them.
(3) UUID: Generates a string-type identifier with a 128-bit UUID algorithm, which is unique in a network (using an IP address). The UUID is encoded as a string of 32-bit 16-digit digits. Similar to. NET generated serial number.
(4) Native: Select one of the identity, sequence or Hilo according to the capabilities of the underlying database. Flexible way, will be based on the use of the database to determine the use of the identity type, MySQL will choose Identity,oracle Select Sequence.
(5) Assigned: Manually develop an identity ID for the entity class. This is the default build policy when the <generator> element is not specified.
(6) Foreign: Use an identifier for another associated object. Commonly used in conjunction with <one-to-one>.
Developers tend to be accustomed to manually configured methods to write configuration properties based on documentation instructions, which is very primitive, and it is helpful for beginners to suggest a manual configuration. There are also a number of third-party tools that configure and then generate XML configuration documents through visualization, improving development efficiencies such as XDoclet, Middlegen, and Andormda.

correlation mapping of multiple pairs of one
The basic mapping of hibernate is discussed above, and an entity class corresponds to a table that uses the <class> tag mapping in the corresponding hibernate mapping file. And the normal properties in the entity class correspond to the table fields, using the <property> tag mapping. In addition, when constructing entity classes, you should note: An parameterless default constructor should be implemented in an entity class, providing a marker, not using the final modifier entity class, generating getter and setter methods for an entity class, and finally introducing several major primary key generation policies, followed by a many-to-many mapping.

This many-to-many correlation mapping reacts to an aggregation relationship in the object model, where user is part of the group, and there are user in the group, and their two life cycles are different and can be reflected in the following diagram:

So how does this mapping of many-to-many relationships be set in hibernate? Here are two ways to use the <many-to-one> tag to map directly, or use the <many-to-one> cascade cascade to modify the table.
1, many-to-one Direct mapping
To be able to understand literally, it refers to a many-to-many relationship, many refers to one end, one refers to the small end, often used in the hbm of many end of the use of the tag, and will <many-to-one> The Name property is set to the attribute at one end of the class that corresponds to the mapping file, such as: <many-to-one name= "group" column= "GroupID" ></MANY-TO-ONE>, The label is added to the User.hbm.xml, which corresponds to the name value in the many label is group pair mapping one, and there is a property named group in User.java. Next look at the specific implementation of the Code class.
(1) User.java class code, which has a property named group that will act as the name value of the one end of <many-to-one>.

public class User { 
 private String name; 
 Public String GetName () {return 
  name; 
 } 
 public void SetName (String name) { 
  This.name=name 
 } 
  
 Private group group; 
 Public Group Getgroup () {return 
  group; 
 } 
 public void Setgroup (group group) { 
  This.group=group 
 } 
} 

(2) The value of <many-to-one>,name in User.hbm.xml is the property value of one end of User.java, which generates a new column in the database that can be interpreted as a foreign key of the User table.

<?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-5-14 23:39:25 by hibernate Tools 3.4.0.cr1--> 
< hibernate-mapping> 
 <class name= "Com.hibernate.User" table= "User" > 
  <id name= "id" type= " Java.lang.Long "> 
   <column name=" ID "/> 
   <generator class=" Assigned "/> 
  </id> 
   
  <!--name's value group is a property in the corresponding one in User.java, which automatically generates a column in the table, so the column is renamed by using column--> 
  <many-to-one name= " Group "column=" GroupID ></many-to-one> 
   
 </class> 

(3) test the above mapping relationship, write two user objects to the table for User1 and User2 respectively, named John and Dick, save objects with session, write data to the database, code as follows:

 public void TestSave1 () {session session=null; 
   try{session=getsession.getsession (); 
    
   Session.begintransaction (); 
   Group Group=new Group (); Group. 
    
   SetName ("Power Node"); 
   User User1=new user (); User1. 
   SetName ("John"); User1. 
    
   Setgroup (group); 
   User User2=new user (); User2. 
   SetName ("Dick"); User2. 
    
   Setgroup (group); 
   Session.save (user1); 
    
   Session.save (User2); will report transientobjectexception error/////Error in scavenging cache transientobjectexception//Because group is transient state, not session, There is no matching data in the database//and user is persistent state, Hibernate cannot find the group object in cache when scavenging cache: Persistent State object cannot refer to transient state object//The problem is 
  In the TestSave2 method, change the Session.gettransaction (). commit (); 
   }catch (Exception e) {e.printstacktrace (); 
  Session.gettransaction (). rollback (); 
  }finally{Getsession.closesession (session); } 
 } 

But using the above code will have an error transientobjectexception when the write is executed because when the user object is saved, it looks up the group object in memory according to the group added in <many-to-one>. However, the above code in the Group object has always been in the transient state, and is not managed by the session, which means that the session object is not found, and the user object entered the persistent state, so it will report this error. The correct code is as follows:

 public void TestSave2 () {session session=null; 
  try{session=getsession.getsession (); 
   
  Session.begintransaction (); 
  Group Group=new Group (); Group. 
  SetName ("Power Node");  Session.save (group); 
  This sets the group object to persistent object user User1=new user (). User1. 
  SetName ("John"); User1. 
   
  Setgroup (group); 
  User User2=new user (); User2. 
  SetName ("Dick"); User2. 
   
  Setgroup (group); 
  Session.save (user1); 
   
  Session.save (User2); The data can be saved correctly//Because both group and user are persistent state objects//So the associated object Session.gettransaction () can be found in the session during Hibernate cleanup cache. Commit ( 
 ); 
  }catch (Exception e) {e.printstacktrace (); 
 Session.gettransaction (). rollback (); 
 }finally{Getsession.closesession (session); } 
} 

2, cascading mapping
In addition to converting the group object and the user object to the persistent object as described above, you can also use the Cascade cascading Mapping property to add the Cascade property to the <many-to-one> property. and is copied to Save-update, which can be written to the database when the group object is not in the persistent state. This requires that you set the Group property of the two user objects to the same group object to achieve a many-to-many mapping, at which point the corresponding content in User.hbm.xml is the following code:

<?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-5-14 23:39:25 by hibernate Tools 3.4.0.cr1--> 
< hibernate-mapping> 
 <class name= "Com.hibernate.User" table= "User" > 
  <id name= "id" type= " Java.lang.Long "> 
   <column name=" ID "/> 
   <generator class=" Assigned "/> 
  </id> 
   
  <!--cascade Modify table--> 
  <many-to-one name= "group" column= "GroupID" cascade= "Save-update" ></many-to-one > 
   
 </class> 
 
 


Note:cascade set to Save-update can be implemented to the database for intermediate modification, add and delete, but the specific cascading query operation is not possible.
The corresponding test configuration file method is the following code:

Cascade Cascade public 
void TestSave3 () {session 
  
 Session=null; 
 try{ 
  session=getsession.getsession (); 
  Session.begintransaction (); 
   
  Group Group=new Group (); 
  Group. SetName ("Power Node"); 
   
  User User1=new User (); 
  User1. SetName ("John"); 
  User1. Setgroup (group); 
   
  User User2=new User (); 
  User2. SetName ("Dick"); 
  User2. Setgroup (group); 
   
  Session.save (user1); 
  Session.save (user2); 
   
  No Transientobjectexception exception thrown 
  //Because cascading 
  //hibernate is used first saves the user's associated object group 
  // Group and user are both objects of the persistent state 
  session.gettransaction (). commit (); 
 catch (Exception e) { 
  e.printstacktrace (); 
  Session.gettransaction (). rollback (); 
 } finally{ 
  Getsession.closesession (session); 
 } 
 

3, contrast sublimation
  Two methods also implement a Many-to-many mapping method, the results are the same, but in the implementation of very different. Either the first or second use is <many-to-one> add the tag to the mapping file at the end of the many. The label's Name property is assigned the value of the property at one end of the class that is registered by the mapping file, which completes the basic mapping of Many-to-many, which is the same point. The difference is that the direct mapping relationship does not adopt the attribute of the Hibernate field, so it is more flexible to implement, not only support addition and deletion, but also query; the second Cascade Cascade modification adopts the Hibernate method, which only supports deletion and modification, and does not support query.

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.