You are on page 1of 6

Java Technologies

By Mr Nataraj

Locking in Hibernate
Posted on 03/02/2013 by Admin

There are 2 kind of locks in Hibernate

Optimistic Lock
Passimistive LockVersioning
Optimistic Locking
In Case of Optimistic Locking,The db row will be locked by Hibernate Java Class.And if any other client tries to update
the same row,it throws Exception.
Lets see that practically
Software/Technology Used:
Java
Oracle Database 11g Express Edition 32Bit
Hibernate 4.1.8

1>Create Product table in system user,and insert a record into that table
SQL>create table productpid number5, pname varchar210,price number10;
SQL> insert into product values101,dvd,100;
2>Develop the Hibernate Application manually

Product.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

publicclassProduct
{
privateintproductId;
privateStringproName;
privatedoubleprice;

publicvoidsetProductId(intproductId)
{
this.productId=productId;
}

publicintgetProductId()
{
returnproductId;
}

publicvoidsetProName(StringproName)
{
this.proName=proName;
}

publicStringgetProName()
{
returnproName;
}

publicvoidsetPrice(doubleprice)
{
this.price=price;
}

publicdoublegetPrice()
{
returnprice;
}

TestClient1.java

importorg.hibernate.LockMode
importorg.hibernate.Session
importorg.hibernate.SessionFactory
importorg.hibernate.Transaction
importorg.hibernate.cfg.Configuration
importorg.hibernate.service.ServiceRegistry
importorg.hibernate.service.ServiceRegistryBuilder

publicclassTestClient1
{

publicstaticvoidmain(String[]args)

Configurationcfg=newConfiguration()

cfg.configure("hibernate.cfg.xml")

//SessionFactoryfactory=cfg.buildSessionFactory()//deprecated

//method,donotuseinHibernate4

//Usethebelow2linestocreateSessionFactoryObject
ServiceRegistryserviceRegistry=newServiceRegistryBuilder()

.applySettings(cfg.getProperties()).buildServiceRegistry()
SessionFactoryfactory=cfg.buildSessionFactory(serviceRegistry)

Sessionsession=factory.openSession()
Productp=(Product)session.get(Product.class,101,

LockMode.UPGRADE_NOWAIT)

Transactiontx=session.beginTransaction()

p.setPrice(122)
try{

Thread.sleep(15000)
}catch(Exceptione){
}
System.out.println("Objectsavedsuccessfully.....!!")
session.saveOrUpdate(p)
//session.flush()

tx.commit()

System.out.println("recordmodified@TestClient1")
session.close()
factory.close()

ClientTest2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

importorg.hibernate.*;
?
importorg.hibernate.cfg.*;
importorg.hibernate.service.ServiceRegistry;
importorg.hibernate.service.ServiceRegistryBuilder;

publicclassTestClient2
{

publicstaticvoidmain(String[]args)
{

Configurationcfg=newConfiguration();
cfg.configure("hibernate.cfg.xml");

//SessionFactoryfactory=cfg.buildSessionFactory();//deprecated
//method,donotuseinHibernate4

//Usethebelow2linestocreateSessionFactoryObject
ServiceRegistryserviceRegistry=newServiceRegistryBuilder().applySettings(cfg.getProperties()).
SessionFactoryfactory=cfg.buildSessionFactory(serviceRegistry);

Sessionsession=factory.openSession();
Productp=(Product)session.get(Product.class,101,LockMode.UPGRADE_NOWAIT);

Transactiontx=session.beginTransaction();
p.setPrice(125);
session.saveOrUpdate(p);
System.out.println("Objectsavedsuccessfully.....!!");

28
29
30
31
32
33
34
35

System.out.println("Objectsavedsuccessfully.....!!");
tx.commit();

session.close();
factory.close();
}

hibernate.cfg.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

<!DOCTYPEhibernateconfigurationPUBLIC
?
"//Hibernate/HibernateConfigurationDTD3.0//EN"
"http://www.hibernate.org/dtd/hibernateconfiguration3.0.dtd">

<hibernateconfiguration>
<sessionfactory>
<propertyname="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<propertyname="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<propertyname="hibernate.connection.username">system</property>
<propertyname="hibernate.connection.password">manager</property>

<propertyname="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<propertyname="show_sql">true</property>
<mappingresource="product.hbm.xml"/>
</sessionfactory>
</hibernateconfiguration>

product.hbm.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14

<!DOCTYPEhibernatemappingPUBLIC
"//Hibernate/HibernateMappingDTD3.0//EN"
"http://hibernate.sourceforge.net/hibernatemapping3.0.dtd">

<hibernatemapping>
<classname="Product"table="product">

<idname="productId"column="pid"/>

<propertyname="proName"column="pname"length="10"/>
<propertyname="price"/>

</class>
</hibernatemapping>

Jars needed in ClassPath


1. ojdbc6.jar
2. antlr2.7.7.jar
3. dom4j1.6.1.jar
4. hibernatecommonsannotations4.0.1.Final.jar
5. hibernatecore4.1.8.Final.jar
6. hibernatejpa2.0api1.0.1.Final.jar
7. javassist3.15.0GA.jar
8. jbosslogging3.1.0.GA.jar
9. jbosstransactionapi_1.1_spec1.0.0.Final.jar
Note:
Collect ojbc6.jar from C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\libCollect all others jars from C:\hibernate
4\lib\required folder

Explaination
1>Compile all the java class after adding jars to classpath
2>Execute TestClient1 using one command prompt
3>Execute TestClient2 using other command prompt immediately after executing TestClient1
TestClient1 has locked the rows with productId=101 for modification purpose.In the same time,if TestClient2 also tries
to lock that row for write purpose,it throws Exception
Download Source Code here
Hope it was a nice Article

Like

Share 12peoplelikethis.
4

Recommend 12peoplerecommendthis.

This entry was posted in Hibernate by Admin. Bookmark the permalink [http://www.nataraz.in/lockingin
hibernate/] .

3 THOUGHTS ON LOCKING IN HIBERNATE

narendra520

Jointhemailinglist
on 07/02/2013 at 8:38 AM said:
the download link is not working sircan u please check it once.

Prasad
on 07/02/2013 at 4:00 PM said:

HI narendra,We have fixed that.Thanks for notifying

emailaddress

Submit

Follow

Follow " Java


Technologies"
Geteverynewpostdeliveredto
yourinbox
Enter email address
Joinmillionsofotherfollowers
Subscribe
PoweredByWPFruits.com

narendra520
on 10/02/2013 at 8:00 AM said:

thanks for responding now i downloaded it

Jointhemailinglist

emailaddress

Submit

Follow

Follow " Java


Technologies"
Geteverynewpostdeliveredto
yourinbox
Enter email address
Joinmillionsofotherfollowers
Subscribe
PoweredByWPFruits.com

You might also like