JPA Find Entity Example

Lokesh Gupta

In JPA, once an entity is persisted in the database, the next thing one typically wants to do is find it again. Let’s see how an entity can be found using the entity manager.

Using EntityManager.find()

In reality, there is really only one line that’s important:

DepartmentEntity department = manager.find(DepartmentEntity.class, 123);

In above line, we are passing in the class of the entity that is being sought and the id or primary key that identifies the particular entity.

This is all the information needed by the entity manager to find the instance in the database, and when the call completes, the department that gets returned will be a managed entity, meaning that it will exist in the current persistence context associated with the entity manager. Passing in the class as a parameter also allows the find() method to be parameterized and return an object of the same type that was passed in, saving the caller an extra cast.

What happens if the object has been deleted or if you supply the wrong id by accident? In the event that the object was not found, then the find() call simply returns null. You would need to ensure that a null check is performed before the next time the department variable is used.

@Override
public DepartmentEntity getDepartmentById(Integer id) {
	return manager.find(DepartmentEntity.class, id);
}

Using JPQL to find entity

Let’s say you want to find all departments then above method will not be able to get you the desired result, because it is able to find only one department entity only at a time. To get all departments, use JPQL in below manner.

public List<DepartmentEntity> getAllDepartments() 
{
	List<DepartmentEntity> depts = manager.createQuery("Select a From DepartmentEntity a",
														DepartmentEntity.class).getResultList();
	return depts;
}

Above query can be modified to return the list of departments based on certain criteria, which you can specify using WHERE clause.

Above code is built and tested using sourcecode provided for this tutorial.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode