I am using hibernate 5 as a JPA implementation and I have an issue with a @OneToMany bidirectinal relationship.
These are my entities:
@Entity(name = "product_item")
public class ProductItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "receptacle")
private Receptacle receptacle;
...
}
@Entity(name = "receptacle")
public class Receptacle {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "receptacle", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<ProductItem> productItems = new HashSet<>();
...
}
I would like this relationship to be lazy in both directions as I want to manually fetch the data through FETCH JOIN like the query below:
String query = "SELECT "
+ " DISTINCT r"
+ " FROM"
+ " receptacle r"
+ " JOIN FETCH product_item pi ON r.id = pi.receptacle.id"
+ " JOIN ereturn er ON er.id = pi.ereturn.id"
+ " WHERE"
+ " r.masterCrossDock IS NULL";
But my problem is that hibernate is ignoring the @ManyToOne(fetch = FetchType.LAZY) hence Jackson breaks due to Infinite recursion (StackOverflowError) through reference chain as shown below:
org.glassfish.jersey.server.internal.process.MappableException: com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: returnitRest.Receptacle["productItems"]->org.hibernate.collection.internal.PersistentSet[0]->returnitRest.ProductItem["receptacle"]->returnitRest.Receptacle["productItems"]->org.hibernate.collection.internal.PersistentSet[0]->returnitRest.ProductItem["receptacle"]- ...
QUESTION 1: How could I tell hibernate not to fetch the @ManyToOne relationship direction?
QUESTION 2: If what I am trying to do is not possible, why?
QUESTION 3: What would be the best way of doing what I am trying to do?
thank you very much
ManyToOne
beingLazy
orEager
. You may need to break that cycle for jackson and I believe you may need to place@JsonIgnore
on one side of the association. – Madhusudana Reddy Sunnapu