Hibernate 如何从一个父级检索所有子级

Hibernate 如何从一个父级检索所有子级,hibernate,jpa,Hibernate,Jpa,我有一个似乎找不到解决办法的问题。我有两个一对多关系的类 UserEntity是父类-该类的一个子类有两个父类。该类也是一个自引用类 @Entity @Table(name = "user") @Component public class UserEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(opt

我有一个似乎找不到解决办法的问题。我有两个一对多关系的类

UserEntity是父类-该类的一个子类有两个父类。该类也是一个自引用类

  @Entity
  @Table(name = "user")
  @Component
  public class UserEntity implements Serializable {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Basic(optional = false)
      @Column(name = "user_id")
      private Integer id;

      @ManyToOne(cascade={CascadeType.ALL})
      @JoinColumn(name="checker_id")
      private UserEntity checker;

      @OneToMany(mappedBy="checker", orphanRemoval=true, cascade = CascadeType.ALL)
      private Set<UserEntity> setters = new HashSet<UserEntity>();

      @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="setter")
      private Set<Module> sModule = new HashSet<Module>();

      @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="checker")
      private Set<Module> cModule = new HashSet<Module>(); 
因此,对于每个用户,我想列出与他们相关的模块。因此,在setter部分,模块将显示在其特定页面上,而在checker部分,相应的模块也将列出

我尝试通过id获取用户并自动获取模块来实现这一点。在本例中,父对象是setter(我使用的是setmodule)。但是该方法返回null

    @Transactional
@SuppressWarnings("unchecked")
public UserEntity getWithModules(Integer id){

    //Retrieve User
    Criteria crit = getCurrentSession().createCriteria(UserEntity.class);
    crit.add(Restrictions.eq("id", id));
    UserEntity userEntity = get(crit);

    //Retrieve the modules for the setter
    crit = getCurrentSession().createCriteria(Module.class);

    crit.add(Restrictions.eq("id", id));

    crit.addOrder(Order.asc("moduleId"));
    Set<Module> sModule = new LinkedHashSet<Module>(crit.list());
    userEntity.setsModule(sModule);  

    return userEntity;
}

我是以正确的方式进行的,还是必须以不同的方式进行设置?我想知道我错过了什么

不应使用条件查询按ID获取实体。有一种方法:
Session.get()
。由于实体之间存在关联,因此也没有理由使用查询来获取此关联

如果我理解正确,您只需要:

UserEntity userEntity = (UserEntity) session.get(UserEntity.class, id);
要获得setter模块,只需调用

userEntity.getSModules();
userEntity.getCModules();
要获得checker模块,只需调用

userEntity.getSModules();
userEntity.getCModules();

嗨,谢谢你的建议。我创建了一个方法,用于通过id获取用户并使用-userEntity.getsModule返回用户。请求具有模块的用户会导致错误-所需的整数参数“userId”不存在