georgiana_e
georgiana_e

Reputation: 1869

JPA circular reference on bidirectional relationship

I have 3 tables like this A----* B * ----- C (* is many, so is bidirectional from A to B and B - C, with many on B, the star indicates many).

A:
@OneToMany(mappedBy = "A")
private List<B> bList;

B:
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
@JsonIdentityReference(alwaysAsId=true)
@ManyToOne
private A;

@ManyToOne
private C;

C:
@JsonIgnore
@OneToMany(mappedBy = "C")
private List<B> bList;

I first retrive the json object, it is retrieved OK, I have eliminated the circular dependencies, but then I want to insert the json I retrieved in DB, on a DB where the object doesn't exist. So I try to save A directly, aRepository.save(A), but then I get an error that C object doesn't exist. How can I save in this case, should I put in the json file in C references to B also? And if yes, how?

EDIT: removed bidirectional relationship between B and C and still not working.

Upvotes: 1

Views: 800

Answers (1)

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

Inserting to Database requires some manipulation of your json since you are dealing with bidirectional relations, see in bidirectional relation each side should have a reference to the other side, this cannot be accomplished exactly in json since we are not dealing with reference so if you have json like this

A {

B [ { A:{} } ]

you cannot tell both A are the same.

So what you really need to do is to retrieve the objects from your json and inject each side of the relation in the other then persist them.

Upvotes: 1

Related Questions