hibernate 联合查询fetch

来源:互联网 发布:巨灵新闻数据库 编辑:程序博客网 时间:2024/06/01 10:17
 实体类student




@Entity
public class Student {
private int id;
private Teacher teacher;
private CommonProperty commonProperty;//组件中有两个实体类属性
public CommonProperty getCommonProperty() {
 return commonProperty;
}
public void setCommonProperty(CommonProperty commonProperty) {
 this.commonProperty = commonProperty;
}
@Id
@GeneratedValue
public int getId() {
 return id;
}
public void setId(int id) {
 this.id = id;
}
@ManyToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)//多对一中多短
@JoinColumn(name="teacher_id")
public Teacher getTeacher() {
 return teacher;
}
public void setTeacher(Teacher teacher) {
 this.teacher = teacher;
}




}


实体类 teacher




@Entity
public class Teacher {
private int id;
private CommonProperty commonProperty;


private  List <Student> students;
private String title;
public String getTitle() {
 return title;
}
public void setTitle(String title) {
 this.title = title;
}
@Id
@GeneratedValue
public int getId() {
 return id;
}
public void setId(int id) {
 this.id = id;
}


public CommonProperty getCommonProperty() {//组件中有两个实体类属性
 return commonProperty;
}
public void setCommonProperty(CommonProperty commonProperty) {
 this.commonProperty = commonProperty;
}
@OneToMany(cascade = CascadeType.ALL,mappedBy="teacher",fetch=FetchType.EAGER )//一对多的一端
public List<Student> getStudents() {
 return students;
}
public void setStudents(List<Student> students) {
 this.students = students;
}




}

List l=session.createQuery("from Student  a inner join   a.teacher").list();//没有加入fecth,这样子就把Student的teacher_id字段和Teacher的id相等的两个对象组合成了一个一维数组,长度为2,分别存放Student和对应的Teacher实体。然后再把这个数组放入到list中。
   (from Student  a inner join fetch  a.teacher where ......     )
  l=session.createQuery("from Student  a inner join fetch  a.teacher").list();//使用了fetch,意思是把Student对应的Teacher实体类放到Student类中的属性teacher中。list中就是student实体类
原文地址:http://blog.163.com/qazwsxzhx@126/blog/static/184431542012126104049352/
特记于此!以备勿忘!