我有两个Java Hibernate实体useruserPick

@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_userUserPick,请在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

09-30 12:27