Home  >  Article  >  Java  >  Detailed introduction to Hibernate for Java transaction management learning

Detailed introduction to Hibernate for Java transaction management learning

黄舟
黄舟Original
2017-03-27 10:28:101593browse

hibernate is a lightweight encapsulation of jdbc. It does not have the ability to manage transactions. At the transaction management level, it is generally entrusted to the underlying jdbc and jta to complete the scheduling. The following article mainly introduces you to the relevant information of Hibernate for Java transaction management learning. Friends in need can refer to it.

Environment and version

hibernate version: Hibernate 4.2.2 (The downloaded file name is hibernate-release-4.2. 2.Final.zip, unzip the directory hibernate-release-4.2.2.Final)

Database: Oracle 10g

Import all jar packages in lib\required

Theoretical Description

1. SessionFactory is responsible for creating Session. SessionFactory is thread-safe. Multiple concurrent threads can access a SessionFactory at the same time. And get the Session instance from it

2. As the core of the persistence manager throughout Hibernate, Session provides numerous persistence methods, such as save(), update, delete, find (in Hibernate 3 This method has been cancelled), etc. Through these methods, we can transparently complete the addition, deletion, modification and check of object (CRUD-- create read update delete). The so-called transparency here means that the Session is reading, creating When deleting instances of mapped entity objects, this series of operations will be converted into operations for adding, modifying, querying, and deleting data in the database table.

Session has the following characteristics

1) It is not thread-safe and multiple threads should avoid sharing the same Session instance

 2) The Session instance is lightweight. The so-called lightweight means that its creation and deletion do not need to consume too many resources

 3) There is a cache inside the Session object , called Hibernate's first cache, it stores objects loaded in the current unit of work, and each Session instance has its own cache.

3. Hibernate Session cache is called Hibernate’s first-level cache. SessionFactory's external cache is called Hibernate's second-level cache. Both caches are located in the persistence layer, and they store copies of database data. SessionFactory's built-in cache stores metadata and predefined SQL. SessionFactory's built-in cache is a read-only cache.

4. The three major functions of Hibernate Session cache:

1) Reduce the frequency of database access and improve access performance.

 2) Ensure that the objects in the cache are synchronized with the database. The objects in the cache are called persistent objects.

 3) When there is an association between persistent objects, Session guarantees that no deadlock of the object graph will occur.

Session How to determine the state change of the persistent object?

Session After loading the object, a snapshot will be copied for the properties of the object value type. When the Session clears the cache, it compares the current object with its snapshot to see which properties have changed.

5. When does the Session clear the cache?

 1)commit() When the method is called

 2) The cache will be cleared when querying to ensure that the query results can reflect the latest status of the object .

 3) Display the flush method of session.

Special case of session clearing cache:

When the object uses the native generator, the cache will be cleared immediately and records will be inserted into the database.

Example code

The test code directory is as follows:

Detailed introduction to Hibernate for Java transaction management learning

hibernate.cfg.xml


<?xml version="1.0"?> 
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
 <session-factory> 
 <property name="show_sql">true</property> 
 <property name="hibernate.connection.driver_class"> 
  oracle.jdbc.driver.OracleDriver 
 </property> 
 <property name="hibernate.connection.url"> 
  jdbc:oracle:thin:@XX.26.158.43:1521:orcl 
 </property> 
 <property name="hibernate.connection.username"></property> 
 <property name="hibernate.connection.password"></property> 
 <property name="dialect">org.hibernate.dialect.OracleDialect</property> 
  
 <mapping resource="com/oscar999/trans/hibernate/Product.hbm.xml"/> 
 </session-factory> 
</hibernate-configuration>

Product.java

/** 
 * @Title: Product.java 
 * @Package com.oscar999.trans.hibernate 
 * @Description: 
 * @author XM 
 * @date Feb 15, 2017 1:44:47 PM 
 * @version V1.0 
 */ 
package com.oscar999.trans.hibernate; 
 
import java.io.Serializable; 
 
/** 
 * @author XM 
 * 
 */ 
public class Product implements Serializable { 
 
 public Product() { 
 } 
 
 private Integer id; 
 
 private String name; 
 
 private String price; 
 
 private static final long serialVersionUID = 1L; 
 
 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 String getPrice() { 
 return price; 
 } 
 
 public void setPrice(String price) { 
 this.price = price; 
 } 
 
}

Product.hbm.xml

<?xml version="1.0"?> 
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" > 
<hibernate-mapping> 
 <class name="com.oscar999.trans.hibernate.Product" table="TEST_PRODUCT"> 
 <id name="id" column="id" type="java.lang.Integer"> 
  <generator class="assigned" /> 
 </id> 
 <property name="name" column="name" type="java.lang.String" 
  not-null="true" unique="true" length="20" /> 
 <property name="price" column="price" type="java.lang.String" 
  not-null="false" unique="false" length="20" /> 
 </class> 
</hibernate-mapping>

TestMain.Java

/** 
 * @Title: TestMain.java 
 * @Package com.oscar999.trans.hibernate 
 * @Description: 
 * @author XM 
 * @date Feb 15, 2017 2:02:17 PM 
 * @version V1.0 
 */ 
package com.oscar999.trans.hibernate; 
 
import java.io.File; 
 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.cfg.Configuration; 
import org.hibernate.service.ServiceRegistry; 
import org.hibernate.service.ServiceRegistryBuilder; 
 
/** 
 * @author XM 
 * 
 */ 
public class TestMain { 
 
 /** 
 * @param args 
 */ 
 
 public Session getSession() { 
 Session session = null; 
 Configuration conf = new Configuration().configure(new File("src/com/oscar999/trans/hibernate/hibernate.cfg.xml")); 
 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry(); 
 SessionFactory sf = conf.buildSessionFactory(serviceRegistry); 
 session = sf.openSession(); 
 return session; 
 } 
 
 public void addProduct(Session session, String name, String price) { 
 Transaction t = session.beginTransaction(); // 1. comment1 
 Product product = new Product(); 
 product.setId(1); 
 product.setName(name); 
 product.setPrice(price); 
 try { 
  session.save(product); 
  t.commit(); // 2. comment2 
 } catch (Exception e) { 
  t.rollback(); 
 } 
 } 
 
 public static void main(String[] args) { 
 // TODO Auto-generated method stub 
 TestMain testMain = new TestMain(); 
 Session session = testMain.getSession(); 
 testMain.addProduct(session, "product1", "price1"); 
 if (session != null && session.isOpen()) { 
  session.close(); 
 } 
 } 
 
}

Instructions:

##1.

20828173aafa67ec3e51b2e888ccffd4
## The generation strategy of #id is specified by yourself, so there is

product.setId(1);

otherwise the addition cannot be successful
2.

Transaction t = session. beginTransaction();


Hibernate itself does not implement its own transaction management function, but a lightweight encapsulation of the underlying JDBC transaction or JTA transaction


3 .Hibernate can be configured as JDBCTransaction or JTATransaction, depending on your configuration in hibernate.properties:

#hibernate.transaction.factory_class net.sf.hibernate.transaction.JTATransactionFactory 
#hibernate.transaction.factory_class net.sf.hibernate.transaction.JDBCTransactionFactory

If you configure nothing, JDBCTransaction is used by default


4. In Hibernate, when the Session is opened, it will automatically

conn.setAutoCommit(false)

, unlike ordinary JDBC, the default is true, so it doesn’t matter if you don’t write commit in the end, because Hibernate AutoCommit has been turned off, so when using Hibernate, if you don't write Transaction in the program, the database will not respond at all.

The relationship between JDBC and Hibernate in transaction processing

Hibernate itself does not implement its own transaction management function, but is a lightweight encapsulation of the underlying JDBC transaction or JTA transaction

Detailed introduction to Hibernate for Java transaction management learning

JTA

JTA来管理跨Session的长事务,那么就需要使用JTATransaction

javax.transaction.UserTransaction tx = new InitialContext();.lookup("javax.transaction.UserTransaction");;


Session s1 = sf.openSession();;
...
s1.flush();;
s1.close();;


...


Session s2 = sf.openSession();;
...
s2.flush();;
s2.close();;


tx.commit();;

Hibernate Transaction是从Session中获得的,tx = session.beginTransaction() ,最后要先提交tx,然后再session.close,这完全符合JDBC的Transaction的操作顺序,但是这个顺序是和JTA的Transactioin操作顺序彻底矛盾的!!! JTA是先启动Transaction,然后启动Session,关闭Session,最后提交Transaction,因此当你使用JTA的Transaction的时候,那么就千万不要使用Hibernate的Transaction,而是应该像我上面的JTA的代码片断那样使用才行。

总结

The above is the detailed content of Detailed introduction to Hibernate for Java transaction management learning. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn