我有两个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())
最佳答案
在User
中与UserPick
关联是可以的。要通过User
中的外键UserPick
关联fk_user
和UserPick
,请在mappedBy = "user"
中添加User
并在User
中将其与UserPick
惰性关联。要指定外键列名,您需要@JoinnColumn(name = "fk_user")
。
@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;
}
而且您可以通过@StanislavL建议的方式来获取用户(除非您不需要为
user
创建别名)public List<UserPick> getAllPicks(){
Criteria criteria = session.createCriteria(UserPick.class)
.setFetchMode("user", FetchMode.JOIN);
return criteria.list();
}
即使与
User
中的UserPick
的关联不是惰性的,这也不是问题,因为Hibernate使用缓存为所有用户的User
设置相同的UserPick
。