Ferhatos Ferhatos - 1 year ago 119
Java Question

Two way relationship with JsonBackReference & JsonManagedReference


I'll solve my problem regarding to this blog Jackson – Bidirectional Relationships

Thanks you.


The problem is about JsonBackReference and JsonManagedReference annotations.
With my two way relationship, I have to explicitly select one way for serialization with JsonBackReference and JsonManagedReference.
But here, I am in case to use the opposit way "Parent->Child" for a specific requierement (using the way "Child->Parent" by default)
When I inversed those two annotations, my JSON is what I'm looking for, for the special requierment.
Any idea on how to use JACKSON in a two way relationship ?

Thank you.


Here is a code simple using EntityGraph (thanks to @NeilStockton suggestion), but still don't serialize the lazy attribute in JSON :-(


public class Parent {
private Long id;

private String parentAttribute;

@OneToOne(mappedBy = "parent", optional = false)
private Child child;


public class Child {
private Long id;

private String childAttribute;

@OneToOne(optional = false, cascade = CascadeType.ALL)
private Parent parent;

Parent Repository

public interface ParentRepository extends CrudRepository<Parent> {

@EntityGraph(attributePaths = { "child" })
//a hack to use findAll with default lazy/eager mapping
Collection<Parent> findByIdNotNull();

Generated query :

parent0_.id as id1_33_0_,
child1_.id as id1_32_1_,
parent0_.parent_attribute as parent_attribute2_33_0_,
child1_.child_attribute as child_attribute2_32_1_,
test.parent parent0_
left outer join
test.child child1_
on parent0_.id=child1_.parent_id
parent0_.id is not null

JSON (no child):

[ {
"id": 1
"parentAttribute": "I am the parent"
} ]

Any idea on how to force Jackson Hibernate4Module to serialize if present ?
Thank you.

I have a Spring Boot 1.3.1 back-office using JPA/hibernate for mapping entities. The front-end is an Angular2 application. The communication is a REST/JSON.
My question is about forcing EAGER loading in some queries when I have a Lazy relationship.
The solution using JOIN FETCH helped me in DAO layer (Repositories). The entity is now completely loaded in a single query as I want in controllers layer. But the serialized JSON still incomplete due to Hibernate4Module.

Bellow Hibernate4Module features can't help :-(






Any idea is welcome. Thanks.

Answer Source

Finally, I solved my problem by using Custom Projection with a constructor in the select part of the query. In the new projection class, there is no "JsonIgnore" or any JPA annotation that make field not serialized by Jackson. I added more data in that projection for reach use. Hope it'll help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download