-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: [JPA] How do i manage entity manager properly?
PostPosted: Sat Jan 24, 2009 7:31 am 
Newbie

Joined: Sat Jan 24, 2009 7:12 am
Posts: 9
Hello everybody.
I've just started implementing Hibernate 3 (JPA) in a legacy project, and have a question about transactions.
I've already read this: http://hibernate.org/42.html, but haven't found an answer there.

I've started reading the "Java Persistence with Hibernate" book, and the author there creates new entity manager for every transaction:


Code:
// Start EntityManagerFactory
EntityManagerFactory emf = Persistence.createEntityManagerFactory("helloworld");

// First unit of work
EntityManager em = emf.createEntityManager();

EntityTransaction tx = em.getTransaction();

tx.begin();

Message message = new Message("Hello World");
em.persist(message);

tx.commit();
em.close();


Is this the right approach, or can i reuse the entityManager as a singleton?
I have a singleton service object, which has an entityManager, and it is reused across all the service methods (CRUD).
What happens if, for example, two threads start using this singleton service simultaneously, i.e. they'll be using that one entityManager object simultaneously - won't it explode or something?


Top
 Profile  
 
 Post subject:
PostPosted: Sat Jan 24, 2009 12:55 pm 
Newbie

Joined: Sat Jan 24, 2009 7:12 am
Posts: 9
i've read some specs on entity manager, and it says that

Quote:
A EntityManagerFactory is an expensive-to-create, threadsafe object intended to be shared by all application threads. It is created once, usually on application startup.

An EntityManager is an inexpensive, non-threadsafe object that should be used once, for a single business process, a single unit of work, and then discarded.


so then i should create the entity manager every time.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.