gozluklu_marti
gozluklu_marti

Reputation: 55

Serialization of @ManyToOne object with customized child object in JPA/Jackson

I have two entity classes with bidirectional @OneToMany/@ManyToOne relationship. When I do serialize Class A, I don't want to have whole Class B inside class A, only the id field. But, class B still needs to appear as an object inside class A and not just a property. How can I achieve that? I am using JPA:2.2/Jackson:2.9.0

@Entity
public class A {

    private long id;

    @ManyToOne
    private B b;

    // ...
}

@Entity
public class B {

    private long id;
    private String str;
    private boolean bool;

    @OneToMany
    Set<A> aList;
    // ...
}

Desired result of Class A:

{
    "id" : 123;
    "b" : {
        "id" : 321;
    }
}

Upvotes: 2

Views: 2362

Answers (2)

J-Alex
J-Alex

Reputation: 7127

There are many ways to achieve this:

1) Ignore properties:

@Entity
public class A {

    private long id;

    @JsonIgnoreProperties({"prop1", "prop2"})
    @ManyToOne
    private B b;
}

2) JsonIdentityInfo and PropertyGenerator. Requires id property.

public class A {
   @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
   @JsonIdentityReference(alwaysAsId = true)
   public B b; 

   public long id;
}

3) JsonValue - indicates a single method/field that should be used to serialize the entire instance.

public class B {

    @JsonValue
    public long id;
}

4) Custom serializer:

@Entity
@JsonSerialize(using = ASerializer.class)
public class A {

    private long id;

    @ManyToOne
    private B b;

    // ...
}

You need to implement ASerializer in this case.

This is a not the easiest but flexible and a granular way of customisation of serialized objects.

See this example.

Upvotes: 0

Alexander Demchik
Alexander Demchik

Reputation: 49

You can try use @JsonIgnoreProperties to ignore certain fields

@Entity
public class A {

    private long id;

    @ManyToOne
    private B b;

    // ...
}

@Entity
public class B {

    private long id;
    private String str;
    private boolean bool;

    @OneToMany
    @JsonIgnoreProperties({"ignoreField1", "ignoreField2"})
    Set<A> aList;
    // ...
}

Upvotes: -1

Related Questions