I have a simple User entity which may have friends (User to User many to many relations) which is mapped in a friends table in database but i don't have a separate Friend entity Object for mapping. Here's the User entity.
@Entity
@Table(name="users")
public class User extends Persistent{
@NotEmpty
@Size(min=4,max=16)
@Column(name="USER_NAME",nullable = false,unique = true)
private String username;
@NotEmpty
@Email
@Column(name="EMAIL",nullable = false,unique = true)
private String email;
@NotEmpty
@Size(min=3,max=99)
@Column(name="PASSWORD",nullable = false)
private String password;
@Column(name="ACTIVE")
private boolean active = true;
@NotEmpty
@Column(name="FIRST_NAME",nullable = false)
private String firstName;
@NotEmpty
@Column(name="LAST_NAME",nullable = false)
private String lastName;
@NotEmpty
@Column(name="DOB",nullable = false)
private String DOB;
@Column(name="PROFILE_PICTURE")
private String profilePicture;
//user activities
@OneToMany(mappedBy = "user",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
private List<Post> posts;
@OneToMany(mappedBy = "user",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
private List<Comment> comments;
@OneToMany(mappedBy = "user",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
private List<Like> likes;
@ManyToMany(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
@JoinTable(name="friends",
joinColumns={@JoinColumn(name="userId")},
inverseJoinColumns={@JoinColumn(name="friendId")})
private List<User> friends;
@ManyToMany(mappedBy="friends",fetch=FetchType.EAGER)
private List<User> friendsWith;
.....
}
So, I have used eager loading to load friends of User. But say if I want to load friends of User without eagerly loading but using JPQL ... Is it possible to use JPQL to loads User friends info since I don't have a Friend Entity class ?? Do i need to create a separate Friend entity class for mapping freinds ??
You have an association between entities. Associations can be loaded eagerly in JPQL using a fetch join:
select distinct u from User u left join fetch u.friends where u.id = :id
This applies whatever the association is, and whatever the way it's mapped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With