Hibernate @OneToMany连接表抛出StackOverflowException

时间:2017-10-08 05:42:32

标签: java hibernate spring-boot kotlin

我正在开发一个hibernate实体关系,设置如下:

用户可以创建作业。用户可以将分配与其他用户分开,为他们分配任务。我的目标是让用户如下:

{id:1,作业:[{name:'test'}],partialAssignment:[{task:'bla'}]}

这样的作业: {id:1,user:{...},assignedUsers:[{...}],...}

分配:

    @Entity
    @Table(name = "Assignment")
    data class Assignment (

      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "id", nullable = false, updatable = false)
      val id: Long? = null,

      @Column(name = "name")
      val name: String? = null,

      @Column(name = "dueDate")
      @Temporal(TemporalType.TIMESTAMP)
      val dueDate: Date? = null,

      @ManyToOne
      @JoinColumn(name = "userId")
      var user: User? = null,

      @OneToMany(mappedBy = "assignment")
      var assignedUsers: List<AssignmentUser> = emptyList()
    )

用户

@Entity
@Table(name = "Users")
data class User (

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, updatable = false)
    @JsonView(UserView.UserSummary::class)
    val id: Long? = null,

    @Column(name = "email", nullable = false)
    @JsonView(UserView.UserSummary::class)
    val email: String = "",

    @Column(name = "password", nullable = false)
    val password: String = "",

    @OneToMany(mappedBy = "user")
    val assignments: List<Assignment> = emptyList(),

    @OneToMany(mappedBy = "user")
    val partialAssignment: List<AssignmentUser> = emptyList()
)

AssignmentUser

@Entity
@Table(name = "AssignmentUsers")
data class AssignmentUser(
    @Column(name = "task")
    val task: String? = null,

    @Id
    @ManyToOne(cascade = arrayOf(CascadeType.ALL))
    @JoinColumn(name = "userId")
    var user: User? = null,

    @Id
    @ManyToOne(cascade = arrayOf(CascadeType.ALL))
    @JoinColumn(name = "assignmentId")
    var assignment: Assignment? = null
) : Serializable {

}

当我使用JPARepository .findOne(id)调用获取Assignment类时,我在Assignment.toString()方法上获得了StackOverflow异常。我不明白为什么,因为它工作正常,直到我添加了psuedo ManyToMany关系(assignedUsers)。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

@OneToMany在这里不会出现问题。

在序列化的情况下(在这种情况下,打印对象的字符串形式),所述代码将进入循环循环。

在陈述的代码片段中,循环关系如下: 1.作业有清单 2. Assignement有用户 3.用户有列表 4.用户有列表 5. AssignmentUser有用户 6. AssignmentUser有作业

在休眠状态下,默认情况下所有映射都设置为LAZY,因此不会导致问题,因为除非需要,否则我们不会加载相关对象。

但是,在序列化的情况下,它将尝试加载关联的对象,因此要打破这一点,我们需要实现自定义序列化。在您的情况下,您需要正确覆盖上述对象的toString方法,即不应该不必要地加载对象。