1

I have question about usage of EntityManager. I've read that is not wise, opening and closing an EntityManager for every simple database call in a single thread!

Is it better to have one EntityManager per all DAO methods or one EntityManager per DAO method?

Mitja Rogl
  • 894
  • 9
  • 22
  • 39

2 Answers2

3

EntityManager should be created, perform a 'Unit of Work', then be closed.

http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html_single/#d0e980

A unit of work would be something like: insert, update, delete, or some more complex business logic. You should get a new EntitiyManager instance for each method, as each method should contain a Unit of Work.

Update: There is also the concept of Extended EntityManager, which would stay open as long as your application is running, or session is open. This would be managed by the container though.

aglassman
  • 2,643
  • 1
  • 17
  • 30
  • Yes but if call two methods I get: `transcation not active`. Is that because I have two differen entity managers? – Mitja Rogl Jun 11 '13 at 11:56
  • 1
    If you are trying to do a transaction across two methods, I believe you'd need to use the same entity manager. – aglassman Jun 11 '13 at 14:21
-1

I will explain you in brief relationship between Entity and DAO.

Consider an example of Online Ship Reservation System which consists of mainly two Entity

1.Admin - Performs add,modify,delete Ship details etc

2.User - Reserve ship tickets online,payment online etc.

In this scenario For Admin entity(add,modify,delete ship details - different kind of function this entity can perform) one AdminDAO is require which will consists of all functions that admin entity can perform.

This entity called from any java servlet class .

In short for each Entity one DAO is require.

Rachana K
  • 104
  • 1
  • 4