如何检索特定关系中存在的所有记录?

时间:2013-11-18 22:53:22

标签: java hibernate hibernate-mapping

我有一类计算机,每一台都可以组装。我需要检索具有Assembler的Computer类的记录。我试过使用标准但无法检索它们。

@Entity
public class Computer{
  ....
  @OneToMany
  private Set <Assembler> assemblers;
  ....
}

@Entity    
public class Assembler{
  ...
  @OneToOne
  private User user;

  @OneToMany
  @LazyCollection(LazyCollectionOption.FALSE)
  private Set<Tools> tools;
  ....
}

@Entity
public class Tools{
   ....
   @OneToOne
   private Electronic electronic;

   @OneToOne
   private Manual manual;

}

代码

 Criteria cre = session.createCriteria(Computer.class, "computer")
                       .createAlias("computer.assembler", "assem")
 cre.add(Restrictions.not(Restrictions.eq("assem.id",null)));
 List computer = (List<Computer>) cre.list();
 System.out.println(computer.size()): << returns zero but should return 1

3 个答案:

答案 0 :(得分:2)

而不是使用:

 cre.add(Restrictions.not(Restrictions.eq("assem.id",null)));

尝试:

 cre.add(Restrictions.isNotEmpty("assemblers"));

(删除别名)

答案 1 :(得分:1)

from Computer computer inner join computer.assemblers as assem

答案 2 :(得分:-1)

List<Computer> list = session.createCriteria(Computer.class).setProjection(Projections.projectionList()
    .add(Projections.property("property.field1")).list();