Hibernate 事务的并发处理

事务定义:数据库事务是指由一个或多个SQL语句组成的工作单元,这个工作单元中的SQL语句相互依赖,如果有一个SQL语句执行失败,就必须撤销整个工作单元。

事务的特性ACID:原子性,一致性,独立性,持久性

 

事务可能出现的问题:

  1. 第一类丢失更新 lost update

  2. 脏读, 读到还没体检的事务数据 dirty read

  3. non-repeatable read 不可重复读

  4. second lost update problem 第二次丢失更新

  5. phantom read 幻读(插入和删除)

只要考虑2,3,5 其他都是特殊情况

 

处理这些问题的解决方案,就是事务的隔离机制:

1,read-uncommitted   2,read-committed  4,repeatable read  8,serializable

只要是数据库支持事务,就不会出现上面的第一种情况(lost update)

read-uncommitted会出现2,3,5的问题

read-committed  会出现 3,5 的问题

 serializable可解决所有问题,但是效率很低

 

所以我们在程序中一般设定Hibernate的隔离级别为2(read-committed )

乐观锁和悲观锁的前提也就是hibernate.conection.isolation=2 也就是隔离级别为read-committed

悲观锁是依赖数据库中的锁,  而乐观锁是在程序中做处理,  所以乐观锁的效率要高

 

下面就先看一个使用悲观锁的简单例子:

package com.lbx.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Account {
	private int id;
	private int balance; //BigDecimal
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getBalance() {
		return balance;
	}
	public void setBalance(int balance) {
		this.balance = balance;
	}
	
	
}

 

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

         
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/testhib</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
       <!--
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property>
        <property name="connection.username">scott</property>
        <property name="connection.password">tiger</property>
      	<property name="dialect">org.hibernate.dialect.OracleDialect</property>
       -->

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache 
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		 -->
		 
		<property name="cache.use_second_level_cache">true</property>
		<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
		<property name="cache.use_query_cache">true</property>
		 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>

        <!-- Drop and re-create the database schema on startup
        <property name="hbm2ddl.auto">update</property>
		 -->
        <mapping class="com.lbx.hibernate.Account"/>
        
    </session-factory>

</hibernate-configuration>

 

package com.lbx.hibernate;

import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.lbx.hibernate.Account;

public class HibernateCacheTest {
	private static SessionFactory sf;
	
	@BeforeClass
	public static void beforeClass() {
		sf = new AnnotationConfiguration().configure().buildSessionFactory();
	}
	@AfterClass
	public static void afterClass() {
		sf.close();
	}
	
	@Test
	public void testSchemaExport() {
		new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
	}
	
	@Test
	public void testSave() {
		Session session = sf.openSession();
		session.beginTransaction();
		
		Account a = new Account();
		a.setBalance(100);
		session.save(a);
			
		session.getTransaction().commit();
		session.close();
	}
	
	//没加悲观锁之前,可能会出问题
	@Test
	public void testOperation1() {
		Session session = sf.openSession();
		session.beginTransaction();
		
		Account a = (Account)session.load(Account.class, 1);
		int balance = a.getBalance();
		//没完成之前做点其他的事
		balance = balance - 10;
		a.setBalance(balance);
		session.getTransaction().commit();
		session.close();
	}
	
	//加了悲观锁之后,就可以解决问题
	@Test
	public void testPessimisticLock() {
		Session session = sf.openSession();
		session.beginTransaction();
		
		Account a = (Account)session.load(Account.class, 1, LockMode.UPGRADE);
		int balance = a.getBalance();
		//do some caculation
		balance = balance - 10;
		a.setBalance(balance);
		session.getTransaction().commit();
		session.close();
	}
	
	public static void main(String[] args) {
		beforeClass();
	}
}

 

 

下面就是一个乐观锁的简单例子(加了个标记version): 

package com.lbx.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Version;

@Entity
public class Account {
	private int id;
	private int balance;
	private int version;    
	@Version
	public int getVersion() {
		return version;
	}
	public void setVersion(int version) {
		this.version = version;
	}
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getBalance() {
		return balance;
	}
	public void setBalance(int balance) {
		this.balance = balance;
	}
	
	
}

 

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

         
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/testhib</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
       <!--
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property>
        <property name="connection.username">scott</property>
        <property name="connection.password">tiger</property>
      	<property name="dialect">org.hibernate.dialect.OracleDialect</property>
       -->

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache 
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		 -->
		 
		<property name="cache.use_second_level_cache">true</property>
		<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
		<property name="cache.use_query_cache">true</property>
		 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>

        <!-- Drop and re-create the database schema on startup
        <property name="hbm2ddl.auto">update</property>
		 -->
        <mapping class="com.lbx.hibernate.Account"/>
        
    </session-factory>

</hibernate-configuration>

 

package com.lbx.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.lbx.hibernate.Account;

public class HibernateCacheTest {
	private static SessionFactory sf;

	@BeforeClass
	public static void beforeClass() {
		sf = new AnnotationConfiguration().configure().buildSessionFactory();
	}

	@AfterClass
	public static void afterClass() {
		sf.close();
	}

	@Test
	public void testSchemaExport() {
		new SchemaExport(new AnnotationConfiguration().configure()).create(
				false, true);
	}

	@Test
	public void testSave() {
		Session session = sf.openSession();
		session.beginTransaction();

		Account a = new Account();
		a.setBalance(100);
		session.save(a);

		session.getTransaction().commit();
		session.close();
	}

	//测试乐观锁
	@Test
	public void testOptimisticLock() {
		Session session = sf.openSession();

		Session session2 = sf.openSession();

		session.beginTransaction();
		Account a1 = (Account) session.load(Account.class, 1);

		session2.beginTransaction();
		Account a2 = (Account) session2.load(Account.class, 1);
		
		a1.setBalance(900);
		a2.setBalance(1100);

		session.getTransaction().commit();   //提交之后,改变了
		System.out.println(a1.getVersion());

		session2.getTransaction().commit();   //所以在这提交再改变数据就报错
		System.out.println(a2.getVersion());

		session.close();
		session2.close();
	}

	public static void main(String[] args) {
		beforeClass();
	}
}

  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值