代码之家  ›  专栏  ›  技术社区  ›  codeme

如何与Kotlin使用JPA-manytomy双向关系

  •  0
  • codeme  · 技术社区  · 6 年前

    我有两个类,它们在Spring启动应用程序中具有双向的多个关系。当我想获取我的实体时,它们开始递归循环,我得到一个stackoverflow异常。这是我的实现。

    @Entity
    @Table(name = "route")
    data class Route(
    
            @Column(name = "uid")
            @Type(type = "pg-uuid")
            @Id
            var uid: UUID,
            var image: String,
            @Column(name = "rate_id")
            var rate_id: UUID,
            @ManyToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY)
            @JoinTable(name = "ach",
                    joinColumns = [JoinColumn(name = "route_id", referencedColumnName = "uid")],
                    inverseJoinColumns = [JoinColumn(name = "athlete_id", referencedColumnName = "uid")])
            var athletes: List<Athlete> = mutableListOf())
    
    @Entity
    @Table(name = "athlete")
    data class Athlete(
    
            @Column(name = "uid")
            @Type(type = "pg-uuid")
            @Id
            var uid: UUID,
            var email: String,
            var image: String,
            @ManyToMany(mappedBy = "athletes")
            var routes: List<Route> = mutableListOf())
    

    1 回复  |  直到 6 年前
        1
  •  6
  •   codeme    6 年前

    @ManyToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY)
    @JoinTable(name = "ach",
               joinColumns = [JoinColumn(name = "route_id", referencedColumnName = "uid")],
               inverseJoinColumns = [JoinColumn(name = "athlete_id", referencedColumnName = "uid")])
    @JsonIgnoreProperties("routes")
    var athletes: List<Athlete> = mutableListOf())
    
    
    @ManyToMany(mappedBy = "athletes")
    @JsonIgnoreProperties("athletes")
    var routes: List<Route> = mutableListOf())
    

    通过添加@JsonIgnoreProperties,可以避免递归循环。