I have defined the JPA Entity Graph on my Entity class, and it looks like follows.
UserTable.java
@Entity
@Table(name = "USER")
@NamedEntityGraph(
name = "user-entity-graph-with-photos",
attributeNodes = {
@NamedAttributeNode(value = "photos"),
})
public class UserTable {
@Id
@Column(name = "USER_ID", nullable = false)
private Long userId;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<PhotoTable> photos = new HashSet<>();
The requirement is that sometimes I want to fetch the users along with the photos, and in some other cases I only want the users to be loaded from the database, but not the photos.
Now, I have created a DAO class for the User - UserDAO.java. In there, I have two methods, each for one case.
public Optional<UserTable> findByEmail(String email) {
final TypedQuery<UserTable> query = entityManager.createQuery(
"SELECT e FROM UserTable e WHERE e.email = :email", UserTable.class);
return Optional.ofNullable(query.setParameter("email", email).getSingleResult());
}
public Optional<UserTable> findByEmailWithPhotos(String email) {
final TypedQuery<UserTable> query = entityManager.createQuery(
"SELECT e FROM UserTable e WHERE e.email = :email", UserTable.class);
return Optional.ofNullable(query
.setParameter("email", email)
.setHint("javax.persistence.loadgraph", entityManager.getEntityGraph("user-entity-graph-with-photos"))
.getSingleResult());
}
I am a bit worried about the API in the DAO layer, since it now contains 2 methods like findByEmail and findByEmailWithPhotos which also loads the photos eagerly. Is this the correct approach? Should we really use one DAO method for each defined entity graph? Would some kind of a builder pattern be more effective here? Any advice is appreciated.
UPDATE
To explain further what I feel is bad about this design is the following. Let's suppose we have 3 entity graphs on the user
user-graph-with-photos
user-graph-with-messages
user-graph-with-followers
Then in the DAO would need to have the following methods:
- findUsers
- findUsersWithPhotos
- findUsersWithMessages
- findUsersWithFollowers
- findUsersWithPhotosAndMessages
- findUsersWithPhotosAndFollowers
- findUsersWithMessagesAndFollowers
- findUsersWithPhotosAndMessagesAndFollowers