@OneToMany协会的标准

时间:2013-08-27 09:55:35

标签: java hibernate

Student类具有与Resume类型的Object的OneToOne关联,Resume类具有与Master类型的集合的OneToMany关联,master具有属性degreeName。 我想要实现的是:

选择student.resume.masters.degreeName所在的所有学生(?,?,?,.....)

它应该搜索所有集合(主)对象。

下面的代码没有编译错误但是没有给出预期的结果请更正我。

学生实体:

 @Entity
 public class Student {
      @OneToOne(fetch = FetchType.LAZY, mappedBy = "student", cascade = CascadeType.ALL)
      private Resume resume;
   }  

恢复实体:

@Entity
public class Resume {
     @OneToMany(mappedBy="resume",cascade=CascadeType.ALL)
     private List<Master> masters=new ArrayList<>();
     @OneToOne(fetch=FetchType.LAZY)
     @PrimaryKeyJoinColumn
     private Student student;
   }  

主要实体:

@Entity
public class Master {
   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   private int id;
   @ManyToOne(fetch=FetchType.LAZY)
   @JoinColumn(name="resume_id")
   private Resume resume;
   private String degreeName;
}

道:

    Criteria studentCriteria = session.createCriteria(Student.class);
    Criteria resumeCriteria = studentCriteria.createCriteria("resume");
    Criteria mastersCriteria = resumeCriteria.createCriteria("masters");
    List<String> degreeslist = new ArrayList<>(Arrays.asList(degrees));
    //degreeList is collection of values on which the student will be searched

    if (degreeslist.size() == 1) {
        mastersCriteria.add(Restrictions.eq("degreeName",
                degreeslist.get(0)));
    } else {

        mastersCriteria.add(Restrictions.in("degreeName", degreeslist));
      }

1 个答案:

答案 0 :(得分:3)

    Criteria mastersCriteria = getSession().createCriteria(Student.class, "student");
    mastersCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);    
    mastersCriteria.createAlias("student.resume", "resume"); 
    mastersCriteria.createAlias("resume.masters","masters");

    if (degreeslist.size() == 1) {
          mastersCriteria.add(Restrictions.eq("masters.degreeName", degreeslist.get(0)));  
    } else {
          mastersCriteria.add(Restrictions.in("masters.degreeName", degreeslist));
    }


    List<Student> students = mastersCriteria.list();