Last week I talked about how to save an entity. And once we’ve saved an entity we’d also like to retrieve it. Compared to managing bidirectional associations or saving entities, retrieving entities is actually rather simple. So simple I doubted whether there would be much point in writing this blog
. However we did use a few nice patterns when writing code for this. And I’m interested to hear what patterns you use to retrieve entities. So here is the next instalment in the series on JPA implementation patterns.
Basically, there are two ways to retrieve an entity with JPA:
- EntityManager.find will find an entity by its id or return null when that entity does not exists.
- If you pass a query string specified in Java Persistence Query Language to EntityManager.createQuery it will return a Query object that can then be executed to return a list of entities or a single entity.
