About Me

My Photo
A Sun certified Java professional with time proven experience in architecture and designing of mid/large scale Java/JEE based applications. Creator of the EasyTest Framework.A lot of experience with technologies such as Spring framework, Hibernate , JPA, Java4-6, REST, SOA , YUI , JUnit , Cloud Foundry PaaS and other technologies.

Tuesday, June 4, 2013

JPA 2 | EntityManagers, Transactions and everything around it

Introduction
One of the most confusing and unclear thing for me, as a Java Developer has been the mystery surrounding the Transaction Management in general and how JPA handles transaction management in particular. When does a transaction get started, when does it end, how entities are persisted, the persistence context and much more. Frameworks like Spring does not help in understanding the concepts either as they provide another layer of abstraction which makes thing difficult to understand. In today's post, I will try to demystify some of the things behind JPA's specification about Entity Management, its transaction specifications and how a better understanding of the concept help us design and code effectively. We will try to keep the discussion technology and framework agonistic although we will look at both Java SE(where the Java EE container is not available) and Java EE based examples.

Basic Concepts

Before diving into greater details lets quickly walk through some basic classes and what they mean in JPA.


  1. EntityManager - A class that manages the persistent state(or lifecycle) of an entity.
  2. Persistence Unit - is a named configuration of entity classes.
  3. Persistence Context - is a managed set of entity instances. The entities classes are part of the Persistence Unit configurations. 
  4. Managed Entities - an entity instance is managed if it is part of a persistence context and that Entity Manager can act upon it.
From bullet point one and three above, we can infer that an Entity Manager always manages a Persistence Context. And so, if we understand the Persistence Context, we will understand the EntityManager.


Details

EntityManager in JPA
There are three main types of EntityManagers defined in JPA.
  • Container Managed and Transaction Scoped Entity Managers
  • Container Managed and Extended Scope Entity Managers
  • Application Managed Entity Managers
We will now look at each one of them in slightly more detail.

Container Managed Entity Manager

When a container of the application(be it a Java EE container or any other custom container like Spring) manages the lifecycle of the Entity Manager, the Entity Manager is said to be Container Managed. The most common way of acquiring a Container Managed EntityManager is to use @PersistenceContext annotation on an EntityManager attribute. Heres an example to define an EntityManager.

public class EmployeeServiceImpl implements EmployeeService { 
    @PersistenceContext(unitName="EmployeeService") 
    EntityManager em; 

    public void assignEmployeeToProject(int empId, int projectId) { 
        Project project = em.find(Project.class, projectId); 
        Employee employee = em.find(Employee.class, empId); 
        project.getEmployees().add(employee); 
        employee.getProjects().add(project); 

    } 

In the above example we have used @PersistenceContext annotation on an EntityManager type instance variable. The PersistenceContext annotation has an attribute "unitName" which identifies the Persistence Unit for that Context.

Container Managed Entity Managers come in two flavors :

  1. Transaction Scoped Entity Managers
  2. Extended Scope Entity Managers
Note that the scope above really means the scope of the Persistence Context that the Entity Manager manages. It is not the scope of the EntityManager itself.

Lets look at each one of them in turn.

Transaction Scoped Entity Manager


 This is the most common Entity Manager that is used in the applications. In the above example as well we are actually creating a Transaction Scoped Entity Manager. A Transaction Scoped Entity Manager is returned whenever a reference created by @PersistenceContext is resolved.
The biggest benefit of using Transaction Scoped Entity Manager is that it is stateless. This also makes the Transaction Scoped EntityManager threadsafe and thus virtually maintenance free. But we just said that an EntityManager manages the persistence state of an entity and the persistence state of an entity is part of the persistence context that get injected into the EntityManager. So how is the above statement on stateless holds ground?
The answer lies in the fact that all Container Managed Entity Managers depend on JTA Transactions. Every time an operation is invoked on an Entity Manager, the container proxy(the container creates a proxy around the entity manager while instantiating it ) checks for any existing Persistence Context on the JTA Transaction. If it finds one, the Entity Manager will use this Persistence Context. If it doesnt find one, then it will create a new Persistence Context and associates it with the transaction.

Lets take the same example we discussed above to understand the concept of entity managers and transaction creation.

public class EmployeeServiceImpl implements EmployeeService { 
    @PersistenceContext(unitName="EmployeeService") 
    EntityManager em; 

    public void assignEmployeeToProject(int empId, int projectId) { 
        Project project = em.find(Project.class, projectId); 
        Employee employee = em.find(Employee.class, empId); 
        project.getEmployees().add(employee); 
        employee.getProjects().add(project); 

    } 

In the above example the first line of assignEmployeeToProject method is calling a find method on the EntityManager. The call to find will force the container to check for an existing transaction. If a transaction exists( for example in case of Stateless Session Beans in Java EE, where the container guarantees that a transaction is available whenever a method on the bean is called) or not. If the transaction doesnt exist, it will throw Exception. If it exists, it will then check whether a Persistence Context exists. Since its the first call to any method of the EntityManager, a persistence context is not available yet. The Entity Manager will then create one and use it to find the project bean instance.
In the next call to find, the Entity Manager already has an associated Transaction as well as the Persistence Context associated with it. It uses the same transaction to find employee instance. By the end of 2nd line in the method both project and employee instance are managed. At the end of the method call, the transaction is committed and the managed instances of person and employee get persisted. Another thing to keep in mind is that when the transaction is over, the Persistence Context goes away.

Transaction Scoped Entity Managers and Read Query Optimisation

If you have queries in your application that fetches entities for read only purpose AND you are using Transaction Scoped Entity Manager (chances of which are very high) then you can do some optimisation of your query. Instead of running your query inside a transaction (by marking your method with @TransactionAttribute), you can run your query outside of the transaction. Since fetch (or find) is immutable, the query will succeed. Also since there is no transaction spawned around the method, the persistence provider does not convert the results of the query into managed entities. This means that the persistence provider does not make a baseline for the returned entities to compare when the transaction is committed. Thus if you have queries that does not modify the returned entities, run them outside of any transaction. You can do this even from within a transactional method by using TransactionAttributeType.NOT_SUPPORTED. Lets see an example:


public class QueryServiceImpl implements QueryService { 
    @PersistenceContext(unitName="PC") 
    EntityManager em; 


    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) 
    public List findAlItems() { 
        return em.createQuery("SELECT item FROM Item item",  
                              Item.class) 
                 .getResultList(); 
    } 

Note that we are saying the entities are not managed if run outside the transaction. It is same as saying the entities are detached and thus any operation done on them that requires conversation with the DB will fail.

Extended Scope Entity Manager

If and when you want the Persistence Context to be available beyond the scope of a method, you use the Entity Manager with extended scope.  The best way to understand the Extended scope Entity Manager is to take an example where the class needs to maintain some state(which is created as a result of some transactional request like myEntityManager.find("employeeId") and then using the employee) and share the state across its business methods.
Because the Persistence Context is shared between method calls and is used to maintain state, it is generally not Thread safe unless you are using them inside a Stateful session bean for which the container is responsible for making it thread safe. To reiterate, in case you are using Java EE Container, Extended Scope Entity Managers will be used inside a Stateful Session Bean( Class annotated with @Stateful) . If you decide to use it outside of the Stateful bean, the container does not guarantee you thread saftey and you have to handle that yourself. Same is the case if you are using third party containers like Spring.

Lets look at an example of Extended Scope Entity Manager in Java EE environment when using Stateful session beans.

Our goal in the example would be to create a business Class that has business methods working on an instance of LibraryUser Entity.  Lets call this business class LibraryUserManagementService that has a business interface UserManagementService. LibraryUserManagementService works on LibraryUsers entity instance . A Library can lend multiple books to the LibraryUser.

Heres an example of Stateful Session bean depicting the above scenario.

@Stateful 
public class LibraryUserManagementService implements UserManagementService { 
    @PersistenceContext(unitName="UserService") 
    EntityManager em; 
    LibraryUser user; 

    public void init(String userId) { 
        user = em.find(LibraryUser.class, userId); 
    } 

    public void setUserName(String name) { 
        user.setName(name); 
    } 

    public void borrowBookFromLibrary(BookId bookId) { 
        Book book = em.find(Book.class, bookId); 
        user.getBooks().add(book); 
        book.setLendingUser(user); 
    } 

    // ... 

    @Remove 
    public void finished() { 
    } 


In the above scenario where we are working with a user instance, it is more natural to get an instance once and then work our way through it and only when we are done, we should persist the user instance. But, the problem is that the Entity Manager is Transaction Scoped. This means that init will run in its own transaction(thus having its own Persistence Context) and borrowBookFromLibrary will run in its own transaction. As a result, user object becomes unmanaged as soon as the init method ends. 

To overcome exactly this sort of problem, we make use of PersistenceContextType.EXTENDED type Entity Manager.

Heres the modified example with PersistenceContextType EXTENDED that will work perfectly.

@Stateful 
public class LibraryUserManagementService implements UserManagementService { 
    @PersistenceContext(unitName="UserService" , type=PersistenceContextType.EXTENDED
    EntityManager em;

    LibraryUser user; 

    public void init(String userId) { 
        user = em.find(LibraryUser.class, userId); 
    } 

    public void setUserName(String name) { 
        user.setName(name); 
    } 

    public void borrowBookFromLibrary(BookId bookId) { 
        Book book = em.find(Book.class, bookId); 
        user.getBooks().add(book); 
        book.setLendingUser(user); 
    } 

    // ... 

    @Remove 
    public void finished() { 
    } 
}
In the above scenario, The PersistenceContext that manages the user instance is created at the Bean initialization time by the Java EE Container and is available until the finished method is called at which time the transaction is committed.

Application Scoped Entity Manager

An Entity Manager that is created not by the container, but actually by the application itself is an application scoped Entity Manager. To make the definition clearer, whenever we create an Entity Manager by calling createEntityManager on the EntityManagerFactory instance, we  actually are creating an application scoped Entity Manager. All the Java SE based applications actually use Application Scoped Entity Managers. JPA gives us a class Persistence that is used to ultimately create an Application Scoped Entity Manager.
Heres an example of how an application scoped EM can be created :

EntityManagerFactory emf = 
            Persistence.createEntityManagerFactory("myPersistenceUnit"); 
        EntityManager em = emf.createEntityManager(); 

Note that for creating an Application Scoped EntityManager, there needs to be a persistence.xml file in the META-INF folder of the application.
EntityManager can be created in two ways. One is already shown above. Another way to create EntityManager is to pass a set of properties as parameter to the createEntityManagerFactory method.

EntityManagerFactory emf = 
            Persistence.createEntityManagerFactory("myPersistenceUnit" , myProperties); 
        EntityManager em = emf.createEntityManager();


If you are creating your own Application Managed Entity Manager, then make sure to close it everytime you are done with using it. This is required because you are now managing how and when the EntityManager should be created and used.

Transaction Management
Transactions are directly related to entities. Managing transactions essentially then would mean managing how entities lifecycle(create, update delete) is managed. Another key to understanding Transaction Management is to understand how Persistence Contexts interacts with transactions. It is worth noting that from an end user perspective, even though we work with an instance of EntityManager, the only role of EntityManager is to determine the lifetime of the Persistence Context. It plays no role in dictating how a Persistence Context should behave. To reiterate, Persistence Context is a managed set of Entity instances. Whenever a transaction begins, a Persistence Context instance gets associated with it. And when a Transaction ends(commits for example), the Persistence Context is flushed and get disassociated with the transaction.

There are two types of Transaction management types supported in JPA. 

  • RESOURCE LOCAL Transactions
  • JTA or GLOBAL Transactions
Resource local transactions refer to the native transactions of the JDBC Driver whereas JTA transactions refer to the transactions of the JEE server. A Resource Local transaction involves a single transactional resource, for example a JDBC Connection. Whenever you need two or more resources( for example a JMS Connection and a JDBC Connection  within a single transaction, you use  JTA Transaction. Container Managed Entity Managers always use JTA transactions as the container takes care of transaction life cycle management and spawning the transaction across multiple transactional resources. Application Managed Entity Managers can use either Resource Local Transactions or JTA transactions. 

Normally in JTA or global transaction, a third party transaction monitor enlists the different transactional resources within a transaction, prepares them for a commit and finally commits the transaction. This process of first preparing the resources for transaction(by doing a dry run) and then committing(or rolling back) is called a 2 phase commit.

Side Note about XA Protocol- In global transactions, a transaction monitor has to constantly talk to different transactional resources. Different transactional resources can speak different languages and thus may not be understandable to the transaction monitor. XA is a protocol specification that provides a common ground for the transaction monitor to interact with different transactional resources. JTA is a global transaction monitor specification that speaks XA and thus is able to manage multiple transactional resources. Java EE compliant servers has implementation for JTA built in. Other containers like Spring write their own or use others implementation(like Java Open Transaction Manager , JBoss TS etc) for supporting JTA or Global transactions.

Persistence Context, Transactions and Entity Managers

A Persistence Context can be associated with either single or multiple transactions and can be associated with multiple Entity Managers. A Persistence Context gets registered with a transaction so that persistence context can be flushed when a transaction is committed. The When a transaction starts, the Entity Manager looks for an active Persistence Context instance. If it is not available it creates one and binds it to the transaction. Normally the scope of the persistence context is tightly associated with the transaction. When a transaction ends, the persistence context instance associated with that transaction also ends. But sometime, mostly in the Java EE world, we require transaction propagation, which is the process of sharing a single persistence context between different Entity Managers within a single transaction.
Persistence Contexts can have two scopes:
  • Transaction Scoped Persistence Context
  • Extended Scoped Persistence Context
We have discussed transaction/extended scoped Entity Managers and we also know that Entity Managers can be transaction or extended scoped. The relation is not coincidental. A Transactional scoped Entity Manager creates a Transaction scoped Persistence Context. An Extended Scope Entity Manager uses the Extended Persistence Context.  The lifecycle of the Extended Persistence Context is tied to the Stateful Session Bean in the Java EE environment.
Let's briefly discuss these Persistence Contexts

Transaction Scoped Persistence Context
TSPC is created by the Entity Managers only when it is needed. Transaction scoped Entity Manager creates a TSPC only when a method on the Entity Manager is called for the first time. Thus the creation of Persistence Context is lazy. If there already exists a propagated Persistence Context, then the Entity Manager will use that Persistence Context.

Understanding of Persistence Context Propagation is important to identify and debug transaction related problems in your code. Let's see an example of how a transaction scoped persistence context is propagated.

ItemDAOImpl.java  :

public class ItemDAOImpl implements ItemDAO { 
    @PersistenceContext(unitName="ItemService") 
    EntityManager em; 

    LoggingService ls; 

    @TransactionAttribute()
    public void createItem(Item item) { 
        em.persist(item); 
        ls.log(item.getId(), "created item"); 
    } 

    // ... 
}  

LoggingService.java :

public class LoggingService implements AuditService { 
    @PersistenceContext(unitName="ItemService") 
    EntityManager em; 
    
    @TransactionAttribute()
    public void log(int itemId, String action) { 
        // verify item id is valid 
        if (em.find(Item.class, itemId) == null) { 
            throw new IllegalArgumentException("Unknown item id"); 
        } 
        LogRecord lr = new LogRecord(itemId, action); 
        em.persist(lr); 
    } 


When createItem method of ItemDAOImpl is called, persist method is called on the entity manager instance. Let's assume that this is the first call to the entity manager's method. The Entity Manager will look for any propagated persistence context with Unit Name "ItemService". It doesn't find one because this is the first call to the entity manager. Thus it creates a new persistence context instance and attaches it to itself. It then goes on to persist the Item object. After the item object is persisted, we then call to log the item information that is just persisted. Note that the LoggingService has its own EnitityManager instance and the method log has the annotation @TransactionAttribute(which is not required if in Java EE envt and the bean is declared to be an EJB).Since the TransactionAttribute has a default TransactionAttributeType of REQUIRED, the Entity Manager in the LoggingService will look for any Persistence Context that might be available from the pervious transaction. It finds one that was created inside the createItem method of the ItemDAOImpl and uses the same one. That is why, even though the actual item is not yet persisted to the Database(because the transaction has not yet been committed), the entity manager in LoggingService is able to find it because the Persistence Context has been propagated from the ItemDAOImpl to the LoggingService.

Extended Persistence Context
Whereas Transaction Scoped Persistence Context is created one for every transaction(in case of non propagation), the Extended Persistence Context is created once and is used by all the transactions within the scope of the class that manages the lifecycle of the Extended Persistence Context. In case of Java EE, it is the Stateful Session bean that manages the lifecycle of the extended Persistence context.  The creation of Stateful Session bean is EAGER. In case of Container Managed Transactions, it is created as soon as a method on the class is called. In case of Application managed Transaction it is created when userTransaction.begin() is invoked.

Summary
A lot of things have been discussed in this blog post, Entity Managers, Transaction Management, Persistence Context , how all these things interact and work with each others.
We discussed differences between Container Managed and Application Managed Entity Managers, Transaction Scoped and Extended scope Persistence Context, Transaction propagation. Most of the material for this blog is a result of reading the wonderful book :  Pro JPA 2 . I would recommend reading it if you want more indepth knowledge of how JPA works. 

23 comments:

naman shah said...

Great Work Dude!

Would like to see more for the latest java ee 7 release ;)

Anuj said...

Thanks Naman. Will soon have few more blogs dedicated to Javaa EE.

Shailesh said...

Thanks a ton Anuj. I was confused with Transaction management.You hv nicely cleared all my doubts here. Looking forward to have some articles on Spring with JPA as well :)

Anuj said...

You are welcome Shailesh. I am glad the blog helped you clear your doubts.
I will try to consolidate an example of using JPA with Spring soon. Stay tuned :)

Anonymous said...

Hey Anuj,

saw your post, it is really very very informative, and reminded me of a problem whose solution is still to be discovered.
actually in one method of a controller i am making calls to 2 different service's 2 differnet methods, and if first service call throws any JPA exception then it should not interrupt my second service call.. Have u ever got into any such situation..

Thanks

Anuj said...

With regard to your problem, it actually depends on a lot of situations.
1) Does your controller method start a transaction(I am assuming not) ?
2) Does each of the service method run in their own separate transaction or they share the transaction.
3) Are you using any third party library (like Spring) to handle your transaction needs?

What is your situation?

congdoan said...

Thanks, you save my life.

Sudheer Kumar said...

I am working in software company in support.I have got some problem when we run a batch file for sending reminder mails.Actullay we used a SELECT query in order to fetch expired rows.But after that a update query is also executed by hibernate which updating corresponding fields.But it should not occur.We dont know root cause.So i want to use readonly=true so that update query will not run.Will it work or not?We are not able to replicate the issue.Please help me

Anuj said...

Hi Sudheer,
It is very difficult for me to comment on your situation given so many variables could come into picture. So I will try to put some points forward which I think may help you in understanding and solving your problem.

1) If you only want to read the data i.e. do a SELECT query , then you ideally should not wrap the method in a Transaction(using @Transactional or @TransactionAttribute whatever the case may be). When you have transactional method that does read only operations, the Persistence Provider manages the entity objects for you. That might not be desirable because you do not intend to update the entity object. Therefore in your situation, I would recommend you to try removing the @TransactionAttribute all together from your batch fetch method and see if that helps. My gut feeling is that will suffice and you actually do not have to make the transaction read only even though it should also ideally work because the attribute readOnly tells Hibernate that the entity objects should not be managed. The difference between using ReadOnly attribute and not using @TransactionAttribute alltogether is that in the former case Hibernate still has to do some extra work of identifying that the transaction should be read only.
I hope it helps in your case.
I am assuming that you do not have your own custom mechanism of handling transactions.

Anuj said...

Sudheer, I also think that you are modifying/changing the entity object in the method that is wrapped around with a transaction and that is why Hibernate is issuing an update command because it sees that the Entity has been modified and so it is dirty and since the entity is still managed (because it is still inside the transaction), Hibernate will issue a flush which will result in an update query. So I strongly feel that you do not have Transaction wrapped around your read only method and that will do the trick.

Sudheer Kumar said...
This comment has been removed by the author.
Sudheer Kumar said...

Hi Anuj,I am really happy with your answer.But I run a method which contains select and update query {using transactionl(readonly=true) }then select query is running and update query is not running.So I want to use Trasactional(readonly=true) in my case specified above and move it to production environment.Because In production even that method is not having trancation.So in order to stop update query i decided to use Trasactional(readonly=true).Please confirm about that.Eagerly waiting for your reply.Thank you in advance

Anuj said...

Sorry Sudheer, I do not understand what exactly you need.
Let me ask few questions and you can say yes or no.
CASE 1: You have a single method wants to do both SELECT and UPDATE on the entity Object: In this case you should use @TransactionAttribute so that your update query can work.
CASE 2: You have a single method that wants to do only SELECT and NO UPDATE : In this case you can either do not use @TransactionAttribute at all or you can use the read only attribute of the Query interface if you are using JPA. So something like this : Query.setReadOnly( true ). Notice that your environment dictates whether this is the right solution or not. For example, you may be using AOP to enable/disable transaction.

Have you tried debugging what exactly is happening if you do not use @TransactionAttribute on the method? Have you enabled Hibernate specific logging like showSql etc.?

May be using @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) will also work. I do not know entirely whether @TransactionAttribute supports readOnly attribute or not in Hibernate. You have to find it out yourself. I know JPA does not support it.

So your choice of solution would be :
1) use Query.setReadOnly(true)
OR
2)@TransactionAttribute(TransactionAttributeType=NOT_SUPPORTED)

Cheers!
Anuj

Sudheer Kumar said...

very very thank you Anuj for your invaluable help during my challenging time.You are responding quickly. thank you once again.

Sudheer Kumar said...

I am facing another issue in my application in which one has to submit big form which contains many data fields and some of dropdown boxes will get data through webservice calls.After submission of form a mail has to be sent to his corresponding office.Here we are persisting data and leaving the transaction commit to Jpa frmework.Here we are using Wicket{user interface}+spring+JPA framework.Some times rarely one or two persons are getting rollback exception while submitting form.Actullay we are persisting data and sending mail but leaving framework to commit that trancaction.So here we dont know the root cause for transaction rollback.So please give some information when will a transaction rollback will happen.Please let me know if you are not able to understand my query.
Thankyou.

Anuj said...

Hi Sudheer,
I cant know the reason for rollback of the transaction in your application as well. THere could be many many reasons for rollback.
Let me briefly explain you how transaction rollback works in JPA. Whenever an exception occurs in your JPA code, Spring marks the transaction for rollback. In your case as well the transaction would be rolled back when an exception occurs.
Now the root cause you have to identify is why it is occurring? Is there an optimistic locking enabled in your application? Are there any collisions between two users. Are there any concurrent persistence happening for the same set of data. There could be many reasons here. I cant predict it for you. What I can suggest you is reading the book Mastering JPA2. It will anser a lot of questions for you. Good luck with your problem.

Sudheer Kumar said...
This comment has been removed by the author.
Sudheer Kumar said...
This comment has been removed by the author.
Sudheer Kumar said...

Hello Anuj,
Could you please give information to solve heapdump issue and memory optimisation of classes in real time applications.You can suggest any tools which can help in solving those type of issues.
Thank you in advance

Ashish said...

Hi Anuj,

I am facing an issue in a web application. When I am using Transactional persistence context, at a point I face lazy initialization issue. To avoid this, I tried using extended persistence context. It works fine and there is no lazy initialization but whenever there is any transaction exception in persist, all subsequent persist call fails (because there is only one persistence context). Please suggest me what should I do.
1- How to overcome lazy initialization issue when using transactional persistence context
2- How to overcome subsequent persist transaction issue if first persist call fails.
3- When to use which (transactional or extended) persistence context.

Anuj said...

Hi Ashish,
It is difficult for me to answer your questions without having an idea of what exactly is the nature of your project. But I will try to answer them anyways:

1) Be aware that Extended Persistence Context is meant for situations where you want the data to be managed across multiple requests. For eg. adding items to shopping cart will imply that every time you hit "Add" on the UI, the call comes to the server, save the item in the already existing list of items and return. It is NOT meant for solving Lazy initialization exceptions.

2) The best way to overcome a Lazy Initialization exception is to understand why it occurs. A lazy initialization exception occurs when you are trying to fetch an entity's related entities outside the scope of the transaction. The best way to avoid Lazy Initialization exception is to explicitly fetch all the data that you need by calling either the getters on the entity or specifying the entity to be eagerly fetched. for eg. a Customer class can have a Set of customer addresses. If you want to access these customer addresses in the UI, then you have to do something like this :

@Entity
public class Customer {

@OneToMany(mappedBy= "cust" , fetch=FetchType.EAGER)
public Set addresses;

}

And then you will not get a lazy initialization exception for addresses field.

Alternately, if you want to fetch the addresses field only sometimes and not always, you can make the above fetchType to be LAZY and then call getAddresses from within your transactional scoped method.

Let me know if you need any more information or clarification.

Ashish said...

Thanks Anuj, If I map my requirement ith your example, I have to keep address FetchType Lazy. I will try the solution the way you described and if could not solve, will bother you once again. :)

Ashish said...

I am using default persistence context i.e. transactional now.
With it, I needed to increase scope of session to avoid lazy initialization issue i.e I have to keep @Transactional on the read method where child entities are also being fetched after parent entity is fetched. Everything works fine so far. Now the problem is that when I my call goes to JBPM flow (in one scenario), somehow it puts lock on row in database(though I am not using any lock and I am not aware if JBPM takes any lock), because of this lock, I am not able to update that row even after JBPM call is over. I am not able to update that row even by making any query from my DB client till I explicitly kill my java process. I am totally stuck here. Please suggest what can be the blocking stone this time ?
Just for your information.
I am using websphere server, DB2 database, XA datasource, JTA and default persistence context.

Thanks