如何从父母一方检索所有孩子

时间:2013-05-04 01:52:16

标签: hibernate jpa

我有问题,似乎无法找到解决方案。我有两个有一对多关系的课程。

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>(); 

因此,在课堂上,与Checker的一对多关系是Setters作为孩子的父母。反过来,Checker和Setter都是Module类的父级。设置器将负责设置模块,而检查器将检查它是否正确。所以两者都与同一模块相关联。

模块

 @Entity
 @Table(name = "modules")
 @Component
 public class Module implements Serializable{

         @ManyToOne(fetch=FetchType.LAZY) 
         @JoinColumn(name="user_id", insertable=false, updatable=false)
         private UserEntity setter;

         @ManyToOne(fetch=FetchType.LAZY) 
         @JoinColumn(name="checker_id", insertable=false, updatable=false)
         private UserEntity checker; 
         ///getters and setters

因此,我希望每个用户都列出与之关联的模块。因此在setter部分中,模块将显示在其特定页面上,而在checker部分中,还将列出相应的模块。

我试图通过id获取用户并自动获取模块来实现此目的。在这种情况下,父级是setter(我正在使用setsModule)。但该方法返回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;
}

上述方法的DAO标准代码

    public T get(Criteria criteria) {
    return (T)criteria.uniqueResult();
    }

我是以正确的方式进行此操作还是以不同的方式进行设置?我会对我所缺少的东西有所了解。

1 个答案:

答案 0 :(得分:0)

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

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

UserEntity userEntity = (UserEntity) session.get(UserEntity.class, id);

要获得setter模块,您只需要调用

userEntity.getSModules();

要获得检查器模块,您只需要调用

userEntity.getCModules();