我有一个简单的用户实体,它可能有朋友(用户到用户多对多关系),这些朋友映射到数据库中的朋友表中,但我没有单独的朋友实体对象进行映射。这是用户实体。
@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;
.....
}
所以,我使用了预先加载来加载User的朋友。但是如果我想加载用户的朋友而不急于加载但使用JPQL ...是否有可能使用JPQL来加载用户朋友信息,因为我没有朋友实体类?我是否需要创建一个单独的Friend实体类来映射freinds?
答案 0 :(得分:1)
您有实体之间的关联。可以使用获取连接在JPQL中急切地加载关联:
select distinct u from User u left join fetch u.friends where u.id = :id
这适用于任何关联,以及它所映射的任何方式。