Hibernate optimistic Lock example

Source: Internet
Author: User

1. Create a new version field in the datasheet, either int or bigint


2. Add a version field to the JavaBean

Package Net.spring.model;

Import Javax.persistence.Column;
Import javax.persistence.Entity;
Import Javax.persistence.Id;
Import javax.persistence.Table;
Import javax.persistence.Version;

@Entity
@Table (name = "T_concurrency") public
class Concurrency {

	@Id
	private int Id;
	
    @Version
	private int Version;

	public int getId () {
		return ID;
	}

	public void setId (int id) {
		this.id = ID;
	}

	public int GetCount () {
		return count;
	}

	public void SetCount (int count) {
		This.count = count;
	}

	@Column
	private int count;

	public int getversion () {
		return version;
	}

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

}

3.dao

	@Transactional (rollbackfor = runtimeexception.class,timeout=10)
	@Override public
	void subtract (int id) { Session
		
		session = NULL;
		
		try {
			session = This.gethibernatetemplate (). Getsessionfactory (). Getcurrentsession ();

			Query query = Session.createquery ("From Concurrency as u where u.id = '" + ID + "'");
			
			Concurrency C = new Concurrency ();
			c = (Concurrency) query.uniqueresult ();

			
			if (C.getcount () > 0) {
				//The first kind does not, not by Hibernate management, hibernate three states in line with, the direct HQL update optimistic lock not effective
				//sqlquery sqlquery = Session.createsqlquery ("Update t_concurrency set count=count-1 where id = '" + ID + "'");
				Sqlquery.executeupdate (); 
				
				C.setcount (C.getcount ()-1);
			}

		} catch (RuntimeException re) {
			throw new runtimeexception ();
			
		} finally {
			if (session! = NULL && sess Ion.isopen ()) {
				session.flush ();
				Session.clear ();}}}
	


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.