Ankit Bansal
Ankit Bansal

Reputation: 2358

Join in Spring Data JPA

I have the following entites

Course

public class Course{

    int courseId;

    int courseName;

    @OneToMany(fetch=FetchType.Lazy,mappedBy="course")
    Set <CourseProperty> courseProp;

    ... setters & getters
}

Course property

public class CourseProperty{

    int courseId;
    int prop1;
    int prop2;
    int prop3;

    @ManyToOne(fetch=FetchType.lazy)
    @JoinColumn(name="courseId",referencedColumnName="courseId",insertable=false, updatable=false)
    @JsonIgnore
    Course course;

    ... setters & getters

}

Now this is the bi-directional join. So I have to place @JsonIgnore in the Course attribute of CourseProp otherwise when I print the course object, it results in infinite loop.

But Now I can't print Course Prop Object with Course Object in it. How do I change my entities. Let Say i want to do query something like

Select * from Course a join CourseProp b on a.courseId = b.courseId and b.prop1="demo" 

I want to run this query(by Spring Data JPA) from CourseProp repository which will result CourseProp Object but becoz of JsonIgnore, I wont get Course Object inside Course Prop.

Upvotes: 0

Views: 104

Answers (1)

chubock
chubock

Reputation: 854

I think it's not a good idea to directly serialize your Entities to JSON with frameworks like Jackson. Because these frameworks try to completely serialize your passing objects to JSON and because your Entities are Hibernate Proxies, it will fetch all the associations of your objects. even those properties that you marked as LAZY and you didn't need them. Also if you have bidirectional relationships in your objects, you will trap in an infinite loop.

Instead, i think it's better to create Model or DTO classes for your Entities and instantiate them with the properties that you need and then serialize those objects to JSON.

Upvotes: 1

Related Questions