Hibernate optimistic Lock Implementation mode

Source: Internet
Author: User


, Student.java

Package com.fgh.hibernate;

Import Java.sql.Timestamp;

public class Student {

	private String ID;

	private String name;

	private int age;

	Private String Cardid;

	Private Timestamp lastdate;

	private int version;

	public int getversion () {return
		version;
	}

	public void setversion (int version) {
		this.version = version;
	}

	Public String GetId () {return
		ID;
	}

	public void SetId (String id) {
		this.id = ID;
	}

	Public String GetName () {return
		name;
	}

	public void SetName (String name) {
		this.name = name;
	}

	public int getage () {return age
		;
	}

	public void Setage (int age) {
		this.age = age;
	}

	Public String Getcardid () {return
		cardid;
	}

	public void Setcardid (String cardid) {
		this.cardid = Cardid;
	}

	Public Timestamp getlastdate () {
	//return lastdate;
	}////Public
	void Setlastdate (Timestamp lastdate) {
	//this.lastdate = Lastdate;
	// }

}

Student.hbm.xml

<?xml version= "1.0"?>
<! DOCTYPE hibernate-mapping public
        "-//hibernate/hibernate mapping DTD 3.0//en"
        "http:// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">
Package com.fgh.hibernate;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.Transaction;

Import org.hibernate.cfg.Configuration;
	public class Hibernatetest {private static sessionfactory sessionfactory;
		static {try {sessionfactory = new Configuration (). Configure (). Buildsessionfactory ();
		catch (Exception e) {e.printstacktrace (); } public static void Main (string[] args) {//Generate two session analog dual-thread concurrent Session Session1 = Sessionfactory.opensession (
		);
		Session Session2 = Sessionfactory.opensession ();
		Transaction tx = NULL;
		Transaction tx1 = null;

		Transaction tx2 = null;
			 try {/** save operation tx = Session.begintransaction ();
			 Student Student = new Student ();
			 Student.setage (20);
			 Student.setcardid ("123");
			 Student.setname ("Zhangsan");
			 Session.save (student);
			Tx.commit (); //Use HQL query: Name Name parameter adjust SetString method for parameter Set value//Then call Uniqueresult method to return unique object Student student1 = (Student) session1. CreateQuery ("from Student s where S.name=:name"). SetString ("name", "Zhangsan"). Uniqueresult (); Student Student2 = (Student) session2.createquery ("from Student s where S.name=:name"). SetString ("name", "Zhang

			San "). Uniqueresult ();
			System.out.println (Student1.getversion ());

			System.out.println (Student2.getversion ());
			Thread 1 modifies the Name property and then commits the transaction to execute thread 1//print out Student2 version 0 because thread 2 transaction has not yet been submitted tx1 = Session1.begintransaction ();
			Student1.setname ("Lisi");
			Tx1.commit ();
			System.out.println (Student1.getversion ());

			System.out.println (Student2.getversion ());  Thread 2 also modifies the Name property, but the Name property has been modified//queried before that name has been updated to Lisi so the place throws an exception staleobjectstateexception//student1 version=1
			Student2 version=0 tx2 = Session2.begintransaction ();
			Student2.setname ("Wangwu");
			
		Tx2.commit ();
			catch (Exception e) {e.printstacktrace ();
			if (null!= tx1) {tx1.rollback ();
			else if (null!= tx2) {tx2.rollback ();
		}} finally {	Session1.close ();
		Session2.close ();
 }
	}
}

Overall implementation results:

Hibernate:select student0_.id as id0_, student0_.version as version0_, student0_.name as name0_, student0_.cardId as card id0_, student0_.age as age0_ from Student_optimistic student0_ where student0_.name=?
Hibernate:select student0_.id as id0_, student0_.version as version0_, student0_.name as name0_, student0_.cardId as card id0_, student0_.age as age0_ from Student_optimistic student0_ where student0_.name=?
0
0
Hibernate:update student_optimistic set version=?, Name=?, cardid=?, age=? where id=? and version=?
1
0
Hibernate:update student_optimistic set version=?, Name=?, cardid=?, age=? where id=? and version=?
Org.hibernate.StaleObjectStateException:Row is updated or deleted by another transaction (or Unsaved-value mapping is I Ncorrect): [com.fgh.hibernate.student#8a8ae4d934d2705b0134d2705cfb0001]
At Org.hibernate.persister.entity.AbstractEntityPersister.check (abstractentitypersister.java:1765)
At Org.hibernate.persister.entity.AbstractEntityPersister.update (abstractentitypersister.java:2407)
At Org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert (abstractentitypersister.java:2307)
At Org.hibernate.persister.entity.AbstractEntityPersister.update (abstractentitypersister.java:2607)
At Org.hibernate.action.EntityUpdateAction.execute (entityupdateaction.java:92)
At Org.hibernate.engine.ActionQueue.execute (actionqueue.java:250)
At Org.hibernate.engine.ActionQueue.executeActions (actionqueue.java:234)
At Org.hibernate.engine.ActionQueue.executeActions (actionqueue.java:142)
At Org.hibernate.event.def.AbstractFlushingEventListener.performExecutions (Abstractflushingeventlistener.java : 298)
At Org.hibernate.event.def.DefaultFlushEventListener.onFlush (defaultflusheventlistener.java:27)
At Org.hibernate.impl.SessionImpl.flush (sessionimpl.java:1000)
At Org.hibernate.impl.SessionImpl.managedFlush (sessionimpl.java:338)
At Org.hibernate.transaction.JDBCTransaction.commit (jdbctransaction.java:106)
At Com.fgh.hibernate.HibernateTest.main (hibernatetest.java:56)
Exception in thread ' main ' org.hibernate.TransactionException:Transaction not successfully started
At Org.hibernate.transaction.JDBCTransaction.rollback (jdbctransaction.java:149)
At Com.fgh.hibernate.HibernateTest.main (hibernatetest.java:63)

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.