我有两个Java Hibernate
实体user
和userPick
:
@Entity
@Table(name="users")
public class User{
@Column(length=50)
private String name;
@OneToMany
private List<UserPick> userPicks = new ArrayList<UserPick>(0);
...
和
@Entity
@Table(name="usersPicks")
public class UserPick {
...
User user; // this line no exist in code
// I want get it when load all picks
// I am confused here or I can do it, because in user is
// List<userPick> and it sounds like circle
// user.getUserPicks().getUser().getUserPicks()....
...
当我加载用户的时候好了。
public User findByUserName(String name) {
Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.eq("name",name));
List<User> users = criteria.list();
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
}
但是我想方设法如何在一个列表中获取所有usersPick's
并获得选择用户,例如:
public List<UserPick> getAllPicks(){
Criteria criteria = session.createCriteria(UserPick.class);
List<UserPick> picks = criteria.list();
return picks;
}
我想打印选择用户名System.out.print(picks.get(0).getUser().getName())
答案 0 :(得分:2)
可以与User
中的UserPick
建立关联。要将User
和UserPick
与fk_user
中的外键UserPick
相关联,请将mappedBy = "user"
添加到User
并与{{{}}建立关联1}}在User
中懒惰。要指定外键列名称,您需要UserPick
。
@JoinnColumn(name = "fk_user")
您可以按@StanislavL建议的方式获取用户(除非您不需要为@Entity
@Table(name="users")
public class User{
@Column(length=50)
private String name;
@OneToMany(mappedBy = "user")
private List<UserPick> userPicks = new ArrayList<UserPick>();
}
@Entity
@Table(name="usersPicks")
public class UserPick {
@ManyToOne(fetch = FetchType.LAZY)
@JoinnColumn(name = "fk_user")
private User user;
}
制作别名)
user
即使与public List<UserPick> getAllPicks(){
Criteria criteria = session.createCriteria(UserPick.class)
.setFetchMode("user", FetchMode.JOIN);
return criteria.list();
}
中的User
的关联不是懒惰也不是问题,因为Hibernate使用缓存为所有用户UserPick
设置相同的User
{1}}。
答案 1 :(得分:1)
criteria.setFetchMode("user", FetchMode.JOIN)
.createAlias("user", "user")
FetchMode.JOIN应解决n + 1查询问题