我想获取有关特定学生的课程详情。我怎么能在Hibernate中做到这一点?
请帮助我进入休眠状态。
@Entity
public class Course implements Serializable {
private long id;
private String name;
@Id
@GeneratedValue
public long getId() {
return id;
}
public String getName() {
return name;
}
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "Enrollment", joinColumns = {
@JoinColumn(name = "Course_Id", insertable = false, updatable = false, nullable = false)}, inverseJoinColumns = {
@JoinColumn(name = "Student_Id", insertable = false, nullable = false, updatable = false)})
private List<Student> students = new ArrayList<Student>();
}
@Entity
public class Student implements Serializable {
private long id;
private String name;
@Id
@GeneratedValue
public long getId() {
return id;
}
}
帮助我查找有关学生课程的详细信息。
答案 0 :(得分:0)
如果单个学生有多个课程,那么您的数据库结构应该是:
@Entity
@Table(name="Student")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID")
private long id;
@Column(name="NAME")
private String name;
@OneToMany(mappedBy="student",fetch = FetchType.EAGER) // change to FetchType.Lazy for lazy initialization
private List<Courses> courses;
// Getters and setters
}
您的课程实体课程应该像
@Entity
@Table(name="Courses")
public class Courses {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="COURSE_ID")
private long id;
@Column(name="COURSE_NAME")
private String name;
@ManyToOne
@JoinColumn(name="Student_ID") // Foreign Key
private Student student;
}
如果遇到延迟初始化的任何问题,请将此属性设置为true &#34; hibernate.enable_lazy_load_no_trans&#34;