我想实现OnetoMany关系两个表的学生和证书。我有两个类,Student和Certificates,它们具有从Student类到Certificates类的OnetoMany关系。休眠OnetoMany的关系
学生类别:
@Entity
@Table(name = "student")
public class Student implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@OneToMany(cascade = CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="student")
private List<Certificats> listCertificats;
// Getters and Setters
Certificats类:
@Entity
@Table(name = "certificates")
public class Certificates implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@ManyToOne
@JoinColumn(name="student_id")
private Student student;
// Getters and Setters
我DAO类必须从数据库中获取数据的方法:
@SuppressWarnings("unchecked")
public List<Students> listStudents() {
List<Students> studentList;
studentList= sessionFactory.getCurrentSession().createQuery("from Student").list();
return studentList;
}
现在,当我运行这个方法,List类的Student类中的listCertificats的值始终为空。但是,我在Student类中获得了id字段的值。我在这里做错了什么?我查了一些关于Hibernate OnetoMany关系的教程,他们用我实现的相同方式描述。任何将非常感激。
我假设你创建测试数据。您是否确保在保存之前建立两个实体之间的关系? (student.getListCertificates()。add(certificate); certificate.setStudent(student)),否则hibernate根据内部会话状态可能会发生意外情况。 –
我比较新。你能详细解释一下吗? –
你需要插入数据到数据库来阅读的东西,我的意思是代码。您使用双向映射。如果使用不当,可能会导致故障 –