Closing JPA entities?


I'm building a simple API to help me learn how to build them in Java. I've come across an issue with closing entities that I don't really understand.

First, I have two classes (projects & clients) which are auto generated by the JPA.

I've built a BaseRespository class and then two other Repository classes which extend it.

package repository;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class BaseRepository {

	public static EntityManagerFactory factory;
	public EntityManager entityManager;
	public BaseRepository() {
		if (BaseRepository.factory == null) BaseRepository.factory = Persistence.createEntityManagerFactory("ProjectApi");
	    if (this.entityManager == null) this.entityManager = factory.createEntityManager();
	public void closeFactory() {
	public void closeEntityManager() {
	public void close() {

Open in new window

And here's the ProjectRepository
package repository;

import java.util.*;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import model.Project;

public class ProjectRepository extends BaseRepository {

	public ProjectRepository() {
	public Collection<Project> all() {
	    Query query = this.entityManager.createQuery("SELECT p FROM Project p ORDER BY name ASC");
	    Collection<Project> projects = (Collection<Project>) query.getResultList();
	    return projects;
	public Project get(Integer projectId) {
		Project project;
		try {
			Query query = this.entityManager.createQuery("SELECT p FROM Project p WHERE id = :id");
			project = (Project) query.setParameter("id", projectId).setMaxResults(1).getSingleResult();
		catch (NoResultException e) {
			project = new Project();
		finally {
		return project;

Open in new window

In my code, I'm using the repository class to return objects from the database;

public class ProjectService {
	private ProjectRepository projectRepo;
	public ProjectService() {
		this.projectRepo = new ProjectRepository();
	public Project get() {
		Project project = this.projectRepo.get(1);
		HashMap response = new HashMap();
		response.put("project", project);
		Response r = Response.status(200).entity(response).build();
		return this.projectRepo.get(1);

	public Response getAll() {
		HashMap response = new HashMap();
		response.put("projects", this.projectRepo.all());
		return Response.status(200).entity(response).build();

Open in new window

The problem I'm having is;
1) I don't know if this is the correct way to be doing it. Using repositories is how I've done this in other languages in order to ensure I'm not writing duplicate code
2) I have absolutely no idea where to close the entityManager and factory. If I close them within the Repository, then the returned objects cannot access any relationships with other objects as the session has been closed.

Some advice would be grateful.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SheppardDigitalAuthor Commented:
I've resolved this myself by using a Filter.

The filter runs before and after the Servlet so I'm able to open and close the connction to the database.

I've created a simple class with a static property which contains the database connection, so it's available to whole application.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SheppardDigitalAuthor Commented:
Resolved myself
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.