Hibernate双向映射不起作用

时间:2016-10-15 06:51:34

标签: java hibernate hibernate-mapping

我有两个表的两个实体。学生与MonthAttendance有一对多的关系。 student_id是连接列。请看下面的代码。

@Entity
@Table(name="student")
public class Student implements Serializable {

    @Id
    @Column(name="student_id")
    @GeneratedValue(strategy= GenerationType.AUTO)
    private String studentId;
/*
*More codes
*/

    @OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
    private Set<MonthAttendance> monthAttendances;
/*
*mutators
*getter and setter methods
*/

}


@Entity
@Table(name="month_attendance")
public class MonthAttendance implements Serializable {

    @Id
    @Column(name="month_year_id")
    @GeneratedValue(strategy= GenerationType.AUTO)
    private String monthYearId;
/*
*More codes
*/
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "student_id")
    private Student student;
/*
*mutators
*getter and setter methods
*/
}

我有DAO课程来从数据库中获取学生数据。我使用下面的代码来获取数据,

List<Student> studentList = session.createQuery("from Student").list();
List<Student> studentList = session.createQuery("from MonthAttendance").list();

两者都运转良好。但是该对象有一个递归结构,例如Student有MonthAttendance,MonthAttendance有Student,再次Student有MonthAttendance继续。 有什么方法可以解决这个问题吗?我只需要一个学生有MonthAttendance,如果我试图让学生,那就没有学生。在此先感谢。

1 个答案:

答案 0 :(得分:0)

为了摆脱这种递归行为,只需删除:

cascade = CascadeType.ALL

来自Student实体,如下所示:

@OneToMany(mappedBy = "student")
private Set<MonthAttendance> monthAttendances;

Cascade基本上说明了这一点:

如果我对某个实体执行某项操作,我该如何对相关实体采取行动。

我应该对它执行相同的操作吗?

我们举个例子:

如果我尝试保存/持久化MonthAttendance对象,Hibernate也会尝试对与其相关的Student对象执行保存/持久操作。为什么?

因为MonthAttendance关联下的Student实体,我们有CascadeType.ALL(在CascadeType.ALL下我们有4到5种操作),这意味着每当你尝试保存/持久{{ 1}} Hibernate尝试在附加的MonthAttendance对象上执行相同的操作(在我们的例子中保存/保留)。

这解释了为什么你得到这种递归行为,因为你用以下方式标记了关联的两面:

Student

当您保存第一个实体时,它会尝试保存第二个实体,第二个实体再次尝试保存第一个实体,依此类推。

相关问题