• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JPA/Hibernate best practices?

 
Aaron Wilt
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic