The moose likes Object Relational Mapping and the fly likes JPA/Hibernate best practices? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Object Relational Mapping
Reply Bookmark "JPA/Hibernate best practices?" Watch "JPA/Hibernate best practices?" New topic
Author

JPA/Hibernate best practices?

Aaron Wilt
Ranch Hand

Joined: Sep 26, 2001
Posts: 49
Hi, I'm new to ORM. I spent a couple days trying to figure it out and I've got some basic stuff working (JPA, annotations, selecting and persisting using native query and jpa query language). Now i want to start designing an approach for my application, so I have some questions related to best practices for JPA.

1. All of my data access is done through DAO objects. I have a baseDAO superclass where in that constructor I create an instance of a protected EntityManager member object and that manager doesn't ever get .close()'d until the finalize() method of my BaseDAO.

Is that ok? Or would it be better to have each method of the DAO call the factory to create/close() a new EntityManager just for the life of the method?

2. Is there a way to detach an Entity from being auto-updated in the database without calling the persist() method? I have a feeling this relates to my manager not being .close()'d until the DAO gets garbage collected...I'd like to be able to change some of my Entity objects database values for display without having the change saved in the db.

3. Let's say I have an Entity with 10 members. I want to do a quick lookup and i'm only going to use 2 of those members for display. What's the best way to tell jpa/hibernate to select and build that entity object with only the data I care about?

Hopefully my questions make sense. if you guys have any links to common JPA practices, that'd be great too.

Thanks,
Aaron
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 16624

OK, unfortunately best practices is a huge topic, one best covered by a book like "Java Persistence with Hibernate" by the guys who created Hibernate from Manning publishing.

But I will say you want to close that EntityManager as soon as possible. Creating new EntityManagers is lightweight. Creating new EntityManagerFactory, yeah that is heavyweight and you want to create a Singleton object to hold it. If you are going to be using EJB3, it gets even easier, your EMF is defined in the persistence.xml and you can now have the container inject EntityManagers into code for you.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
 
 
subject: JPA/Hibernate best practices?
 
Threads others viewed
Lazy loading exception in presentation layer, what's the nicest way to avoid them?
Using Hibernate EntityManager
EJB3 Beta Certification - EntityManager BASIC notes.
Generic DAO using Spring
EJB3 Beta Certification - Help =))
IntelliJ Java IDE