geronimo-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From David Blevins <david.blev...@visi.com>
Subject Re: JPA, entities and EJB3
Date Thu, 12 Jun 2008 16:57:22 GMT
Definitely if you intend to use UserTransaction I would absolutely go  
with a TRANSACTION scoped unit and then use @PersistenceContext  
EntityManager.  Once you call joinTransaction you end up paying the  
cost of a JTA transaction but don't get any of the benefits.  One of  
those benefits would make it impossible for you to make the mistake  
you made.  Very good learning experience though, and you're lucky you  
found this quickly!


In this particular code that you posted you're creating two  
EntityManagers in the same JTA transaction and they are competing  
against each other.  As I mentioned, EntityManagers created from a  
RESOURCE_LOCAL/EntityManagerFactory do not cooperate with anyone.   
Each EntityManager represents a cache and has it's own non-shared  
database connection, etc.

So here's what the implications of that are, for simplification  
reasons we'll say the accountNumber variable is 12345:

  - Method1: you create a private database Cache, we'll call it  
PersistenceContext A (i.e. you create an EntityManager)
  - Method1: a JTA transaction is begin via UserTransaction.begin();
  - Method1: you call joinTransaction on PersistenceContext A  
instructing it to flush it's cache when the JTA transaction ends.
  - Method1: you ask PersistenceContext A to find Account 12345,  
PersistenceContext A does yet have a copy of that date, thus it will  
pull the data from the database and into the cache of  
PersistenceContext A.
  - Method1: updates to Account 12345 are done against the *cached  
copy* in PersistenceContext A.
  - Method2: you create a *second* private database Cache,  
PersistenceContext B (i.e. you create an EntityManager)
  - Method2: you call joinTransaction on PersistenceContext B  
instructing it to flush it's cache when the JTA transaction ends.
  - Method2: you ask PersistenceContext B to find Account 12345,  
PersistenceContext B does yet have a copy of that date, thus it will  
pull the data from the database and into the cache of  
PersistenceContext B.  You now have *two* separate and competing  
copies of Account 1234 in the transaction, in in the cache of  
PersistenceContext A and one in the cache of PersistenceContext B.
  - Method2: updates to Account 12345 are done against the *cached  
copy* in PersistenceContext B.
  - Method1: more up  to Account 12345 are done against the *cached  
copy* in PersistenceContext A.
  - Method1: the JTA transaction is committed and PersistenceContext A  
and PersistenceContext B are each individually notified to flush their  
caches.

At this point there's no guarantee who will win, A or B.  But based on  
your results it's pretty clear A got to the database before B,  
therefore B was the last person to update the record. I.e.:

  - PersistenceContext A flushed it's cache and executed "ACCOUNT  
12345 BALANCE = 7000"
  - Then PersistenceContext B flushed it's cache and executed "ACCOUNT  
12345 BALANCE = 6000"


So the moral of this story is that the concept of a database cache is  
an extremely important concept to be aware of.  Without a copy of the  
data in memory (i.e. a cache) when you call account.getBalance() the  
persistence provider would have to go read the value from the database  
every time.  This would obviously be a big waste of resources.  The  
other side of having a cache is that when you call  
account.setBalance(5000) it also doesn't hit the database (usually).   
When the cache is "flushed" the data in it is sent to the database via  
as many SQL updates, inserts and deletes as are required.  That is the  
basics of java persistence of any kind all wrapped in a nutshell.  If  
you can understand that, you're good to go in nearly any persistence  
technology java has to offer.

With this in mind, the explanation I posted before will likely take on  
a whole new light.  Here's a slightly reworded/abbreviated version:

A RESOURCE_LOCAL persistence unit: The implication of the  
RESOURCE_LOCAL is that the EntityManager instance you create from the  
factory *is* the entire persistence context, cache and all.  For  
illustrative purposes it's safe to imagine big "cache" hashmap as a  
field inside the EntityManager instance you created.  If you want  
someone else to do persistent operations with the same persistence  
context you need to find a way to get them the exact EntityManager  
instance you created (not a second EntityManager they create).


A TRANSACTION persistence unit: With TRANSACTION, everyone in the  
transaction shares the same EntityMangaer.  As a vendor what we do  
underneath the covers is give you an EntityManager wrapper that points  
to nothing.  Then when a transaction is started (via UserTransaction  
or a container transaction) we use the EntityManagerFactory to create  
an EntityManager instance and make all the wrappers point to it.  When  
the transaction commits, the cache associated with the internal  
EntityManager instance is flushed and the EntityManager instance is  
discarded and all EntityManager wrappers again point to nothing.  This  
is essentially why you need a transaction in progress to use a  
EntityManager with JTA scope and TRANSACTION unit, because the  
EntityManager you hold onto doesn't represent a real EntityManager  
rather just a "fake" EntityManager that directs all calls you make on  
it to the container's internal EntityManager that is associated with  
the JTA transaction you're in.  If there is no JTA transaction in  
progress, there is no internal EntityManager and the EnityManager  
wrappers therefore point nowhere.


-David

On Jun 12, 2008, at 5:02 AM, Phani Madgula wrote:

> Thanks for providing useful. Now the intricacies are becoming clear  
> indeed !!
> I am trying to guess what could/should be the outcome of the  
> following scenario.
>
> ***************
>    @PersistenceUnit(unitName="AccountUnit")
>    EntityManagerFactory emf;
>
> [..]
>     private void method1(int accountNumber, PrintWriter out)
>     throws Exception{
>
>         try{
>             EntityManager em = emf.createEntityManager();
>
>             Context ctx = new InitialContext();
>             UserTransaction ut =  
> (UserTransaction)ctx.lookup("java:comp/UserTransaction");
>
>             ut.begin();
>
>             em.joinTransaction();
>
>             Account account = em.find(Account.class, accountNumber);
>
>             account.setBalance(5000);
>
>             method2(accountNumber,out);
>
>             account.setBalance(7000); (this update is missing in the  
> table)
>
>             ut.commit();
>
>
>         }catch(Exception e){
>             throw e;
>         }
> }
>
>     private void method2(int accountNumber, PrintWriter out)throws  
> Exception {
>
>         try{
>             EntityManager em = emf.createEntityManager();
>
>             em.joinTransaction();
>
>             Account account = em.find(Account.class, accountNumber);
>
>             account.setBalance(6000);
>
>
>         }catch(Exception e){
>             throw e;
>         }
>
>     }
> ********************************
>
> What I observed from the above code is account.setBalance(7000);  
> (this update is missing in the table). The value of balance column  
> will be 6000. The last update in the method (to 7000) misses.
>
> Thanks
> Phani
>
> On Thu, Jun 12, 2008 at 7:44 AM, David Blevins  
> <david.blevins@visi.com> wrote:
>
>
> On Jun 9, 2008, at 1:43 AM, Phani Madgula wrote:
>
> Hi,
> I have tried to play with <jta-datasource> and <non-jta-datasource>  
> as follows.
>
> I have the following peristence.xml in a web application.
> [...]
>
>
>   <persistence-unit name="Tutorial" transaction-type="RESOURCE_LOCAL">
> [...]
>
>
> In the servlet, I have the following code
> [...]
>
> @PersistenceContext(unitName="Tutorial")
>  private EntityManager em;
> .....
> ....
>                UserTransaction ut;
>                try{
>                        Context ctx = new InitialContext();
>
>                        //ut = (UserTransaction)ctx.lookup("java:comp/ 
> UserTransaction");
>                        //ut.begin();
>
> //Uncomment EntityTransaction
>                        EntityTransaction et = em.getTransaction();
>                        et.begin();
>
>                        Book book = new Book("DDDDD","John", 
> 1.0,"Joe","1934834-23823","Phani");
>                        em.persist(book);
>
>                        et.commit();
>                        //ut.commit();
>
>                }catch(Exception e){
>                        e.printStackTrace();
>                        throw new ServletException (e);
>                }
>  ***********************
>  I get the following error
>  ***********************
>
>  java.lang.IllegalStateException : You can not call getTransaction on
> a container managed EntityManager
>
> [...]
>
>
> Please note that I am using "RESOURCE_LOCAL" persistence unit.
>
> You're in the right direction.  Try modifying this part of your  
> servlet as follows:
>
> [cut this part]
>
> @PersistenceContext(unitName="Tutorial")
> private EntityManager em;
>
> [redo as]
> @PersistenceUnit(unitName="Tutorial")
> private EntityManagerFactory emf;
>
>
> The use of RESOURCE_LOCAL definitely requires you to use the  
> EntityTransaction API as you were attempting to do.  It also  
> requires you to use the EntityManagerFactory to get your  
> EntityManager.  The implication of the RESOURCE_LOCAL is that the  
> EntityManager instance you create from the factory *is* the entire  
> persistence context, cache and all (EntityManger instance ==  
> PersistenceContext, terminology wise).  For illustrative purposes  
> it's safe to imagine big "cache" hashmap as a field inside the  
> EntityManager instance you created.  It's not entirely how most  
> providers do it, but the technical ramifications are the same.  One  
> of the ramifications is that if you want someone else to do  
> persistent operations with the same persistence context you need to  
> find a way to get them the EntityManager instance you created.  From  
> a spec perspective we (EJB 3.0 spec hat on) could have allowed you  
> to reference a RESOURCE_LOCAL unit via an EntityManager reference,  
> but the trick is that each reference would wind up creating a new  
> EntityManager instance, cache and all, and you could make a really  
> big mess; seemed better to just force you to create the instance  
> yourself and share it however you feel best so that there could be  
> no misunderstandings.
>
> With a TRANSACTION unit you are in fact required to lookup or have  
> injected the EntityManager and are not allowed to use the  
> EntityManagerFactory or the EntityTransaction API.  As a vendor what  
> we do underneath the covers is give you an EntityManager wrapper  
> that points to nothing.  Then when a transaction is started (via  
> UserTransaction or a container transaction) we use the  
> EntityManagerFactory to create an EntityManager instance and make  
> all the wrappers point to it.  When the transaction commits, the  
> internal EntityManager instance is discarded (cache goes bye-bye)  
> and wrappers again point to nothing.  This is essentially why you  
> need a transaction in progress to use a EntityManager with JTA scope  
> and TRANSACTION unit.  With an EXTENDED PersistenceContext (again,  
> available only with a TRANSACTION unit) things work pretty much the  
> same except that the internal EntityManager instance is *not*  
> discarded and the end of transactions (cache stays in memory and can  
> be used again in another transaction), instead it lives as long as  
> the Stateful session bean holding it.
>
>
> My questions are
>
> 1. Should we always use UserTransaction object irrespective of
> <jta-datasource> or <non-jta-datasource> in JEE environment??
>
> 2. How is the use of <non-jta-datsource> different from the use
> <jta-datasource> in JEE environment??
>
> 3. In EJBs, when ContainerManaged Transactions are used, there is no
> need to use JTA. Is that correct??
>
> 4. Only in J2SE environments, we can use EntityTransaction object. is
> that correct??
>
> Hopefully the above explanation answers these questions (good  
> questions, BTW).  If anything is still unclear, definitely don't  
> hesitate to ask for more information or for something to be simply  
> reworded (can be hard trying to find the right way to explain these  
> things).
>
>
> -David
>
>
> On 5/28/08, David Jencks <david_jencks@yahoo.com> wrote:
> 1. I hope you named the file openejb-jar.xml
> 2. jta-datasource and non-jta-datasource have to contain the names of
> the datasources in the geronimo plan used for the pool, NOT some jndi
> name you might also map them to.  The datasources don't need to be
> bound in jndi in order to be used for jpa
> 3. The non-jta-datasource must be a datasource that really has no
> transaction support, using the <no-transaction/> element instead of
> <local-transaction/> or <xa-transaction>... in the connector plan.
> With derby I find it necessary to have a non-jta-datasource if any ddl
> is needed or if openjpa is generating the primary keys.  I don't know
> if you can get away without one for other databases.  If you want to
> experiment, leave out the non-jta-datasource rather than duplicating
> the jta-datasource contents.
>
> hope this helps
> david jencks
>
> On May 27, 2008, at 4:09 PM, zeros wrote:
>
>
> Good evening:
>
>  I'm newbie with EJB3.0. I want to configure the persistence.xml
> to have
> entities managed with JPA. I have the next configuration files:
> OPENJPA-JAR.XML
>
> <openejb-jar xmlns="http://www.openejb.org/xml/ns/openejb-jar-2.1"
> xmlns:nam="http://geronimo.apache.org/xml/ns/naming-1.1"
> xmlns:pkgen="http://www.openejb.org/xml/ns/pkgen-2.0"
> xmlns:sec="http://geronimo.apache.org/xml/ns/security-1.1"
> xmlns:sys="http://geronimo.apache.org/xml/ns/deployment-1.2">
> <sys:environment>
>  <sys:moduleId>
>    <sys:groupId>o2o.marketing</sys:groupId>
>    <sys:artifactId>EJB</sys:artifactId>
>    <sys:version>1.0.8</sys:version>
>    <sys:type>jar</sys:type>
>  </sys:moduleId>
>  <sys:dependencies>
>      <sys:dependency>
>          <sys:groupId>console.dbpool</sys:groupId>
>        <sys:artifactId>marketing</sys:artifactId>
>        <sys:version>1.0</sys:version>
>                <sys:type>rar</sys:type>
>                </sys:dependency>
> </sys:dependencies>
> </sys:environment>
> </openejb-jar>
>
> And I have also persistence.xml
>
> <?xml version="1.0" encoding="UTF-8"?>
> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence
> "
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
> http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
> <persistence-unit name="marketing">
>        <description>Entity Beans for User</description>
>
> <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</
> provider>
>        <jta-data-source>java:comp/env/marketing</jta-data-source>
>        <non-jta-data-source>java:comp/env/marketing</non-jta-data- 
> source>
>      <mapping-file>META-INF/orm.xml</mapping-file>
>      <properties />
> </persistence-unit>
> </persistence>
>
> The error which I'm having is the next one: Unable to resolve
> reference
> "JtaDataSourceWrapper" and Unable to resolve reference
> "NonJtaDataSourceWrapper", which are basically the same error.
>
> I think this is produced because I'm not mapping the Datasocurce to
> the
> DBPool. Geronimo returns to me examples to do it for web, but no
> example to
> do it for an EJB.
>
> Please could you help me?
>
> WATCH OUT! I'm talking about entities and EJB3.0, not entiti beans and
> EJB2.0
>
> Thanks in advance
>
> SERGIO
> --
> View this message in context:
> http://www.nabble.com/JPA%2C-entities-and-EJB3-tp17502079s134p17502079.html
> Sent from the Apache Geronimo - Users mailing list archive at
> Nabble.com.
>
>
>
>
>
>


Mime
View raw message