Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JPA ManyToMany bidirectional relation with Kotlin

I have two classes which have bidirectional ManyToMany relations in a Spring Boot application. When I would like to fetch my entities, they start recursively looping, and I get a stackoverflow exception. These is my implementation.

@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())

I understand that the problem is that both of my list attribute is in the constructor. However I would like to have the list attributes in the response. I have seen solutions where the toString method was overwritten to create a json string. I would prefer to return an object instead of a jsonString. Is there a way to implement the above problem with or without dataclasses? Please give some example if there is a way.

like image 959
codeme Avatar asked Oct 19 '25 17:10

codeme


1 Answers

Please notice that this answer is solution for Kotlin data classes with ManyToMany bidirectional relation.

@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())

With adding the @JsonIgnoreProperties, you can avoid the recursive loop.

like image 70
codeme Avatar answered Oct 21 '25 23:10

codeme