Java hibernate获取所有实体

时间:2016-01-26 12:35:02

标签: java hibernate

我有两个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())

2 个答案:

答案 0 :(得分:2)

可以与User中的UserPick建立关联。要将UserUserPickfk_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查询问题