hibernate之控制并发访问(乐观并发控制之外获得额外的隔离性保证--使用LockMode.UPGRADE的实例)

LockMode.UPGRADE锁模式可以禁止不可重复读取发生。

 

pom.xml:

4.0.0 hibernateTest hibernateTest 1.0-SNAPSHOT jar hibernateTest http://maven.apache.org junit junit 3.8.1 jar test false org.hibernate hibernate-core 3.3.1.GA jar false org.slf4j slf4j-nop 1.5.2 jar false javassist javassist 3.4.GA jar false c3p0 c3p0 0.9.1 jar false com.oracle ojdbc14 10.2.0.3.0 jar runtime false hibernateTest src/main/resources src/main/java **/*.java maven-compiler-plugin 1.6 1.6 UTF-8  

 

resources/hibernate.cfg.xml:

oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@localhost:1521:XE true gbk system password 20 5 120 100 120 2 org.hibernate.dialect.OracleDialect true true true  

 

pojo/User.java:

package pojo; import java.io.Serializable; import java.util.Date; public class User implements Serializable { private String id; private String name; private String password; private int age; //时间戳版本,好像这里只能用Date private Date updateTime; public String getId() { return id; } @SuppressWarnings("unused") private 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getUpdateTime() { return updateTime; } }  

 

pojo/User.hbm.xml:

 

 

util/HibernateUtil.java:

package util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory; static{ try { sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable e) { throw new ExceptionInInitializerError(e); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static void shutdown(){ getSessionFactory().close(); } }  

 

util/Manager.java:

package util; import org.hibernate.LockMode; import org.hibernate.Session; import org.hibernate.Transaction; import pojo.User; public class Manager { public static void main(String[] args) { User user = new User(); user.setAge(22); user.setName("jjjjj"); user.setPassword("5555"); Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); session.save(user); /** * 第一种方法 * 显示的悲观锁,锁模式为:LockMode.UPGRADE * User user1 = (User) session.get(User.class, "402881792b8790c5012b8790c6650001",LockMode.UPGRADE); */ /** * 第二种方法 */ User user1 = (User) session.get(User.class, "402881792b8790c5012b8790c6650001"); session.lock(user1, LockMode.UPGRADE); user1.setName("fhd001"); transaction.commit(); session.close(); } }  

 

表结构:

A_USER_ONE表: ID, NAME, PASSWORD, AGE, UPDATETIME 

你可能感兴趣的:(hibernate)