Hibernate Version tutorial with example


Hibernate Version management


The <version> element is optional and indicates that the table contains versioned data. This is particularly useful if you plan to use long transactions, Version tag may help you to avoid concurrent updation for a row.


 	<version name="count" column="hits"></version>

Code

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.candidjava.hibernate.Student" table="userstest">
		<id name="id" column="id">
			<generator class="increment" />
		</id>
		<version name="count" column="hits"></version>
		<property name="name" column="fname" not-null="true" />
		<property name="degree" column="degree" />
		<property name="phone" column="mobile" />
		<property name="email" column="priEmail" />

	</class>

</hibernate-mapping>

Updating versioned record

public void updateStd() {
		try {
			Session s = getSession();
			Transaction tx = s.beginTransaction();
			Student user = (Student) s.get(Student.class, student.getId());
			user.setName(student.getName());
			user.setEmail(student.getEmail());
			user.setDegree(student.getDegree());
			user.setPhone(student.getPhone());
			Thread.sleep(1000); // delay the update to do concurrent test
			s.update(user);
			tx.commit();
		} catch (HibernateException | InterruptedException e) {
			System.out.println(e.getMessage());
			System.out.println("updation failed");
		}
	}

Test Concurrency

Student sa=new Student();
		sa.setId(1);
		sa.setName("raman");
		sa.setEmail("raman@mail.com");
		sa.setPhone("9557857");
		sa.setDegree("bca");

		Student sas=new Student();
		sas.setId(1);
		sas.setName("ramaaaan");
		sas.setEmail("ramaaan@mail.com");
		sas.setPhone("953358775");
		sas.setDegree("Mca");

		StudentDao ms=new StudentDao();
		ms.setStudent(sa);
		
		StudentDao mss=new StudentDao();
		mss.setStudent(sas);
		
		ms.start();
		mss.start();

Download

Hibernate Version example war

Hibernate version example zip





Comments


©candidjava.com