HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / JPA / Find Entity Example

JPA Find Entity Example

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.

Download Sourcecode

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces