I have following classes:
public class Entity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
private String name;
@JsonManagedReference
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Category category;
//Constructors, getters and setters
}
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
private String name;
@JsonBackReference
@OneToMany(mappedBy = "category", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Entity> entity;
//Constructors, getters and setters
}
I have a form where when I submit the form I get following JSON:
{
id: "1"
name: "EntityA"
category: {
id: "4"
name: "categoryA"
}
}
CategoryA is already in database. When I persist EntityA object (main object) to database BOTH objects will be persisted.
What's wrong with it?
Problem is that category is going to be persisted again with same information but with different id. So when I persist the above object EntityA is persisted fine in database, but category is persisted again with different id even if it exist in database.
So here's the steps with databse point of view.
Initial database:
Entity table (empty)
|id | name | category_id |
--------------------------
| | | |
Category table
| id | name |
----------------
| 4 |categoryA|
Entity_category table (empty)
| entity_id | category_id |
---------------------------
| | |
After persisting
Entity table (empty)
id | name | category_id |
--------------------------
1 |EntityA| 5 |
Entity_category table (should not be empty, but is empty)
| entity_id | category_id |
---------------------------
| | |
Category table
id | name |
--------------
4 |categoryA|
5 |categoryA|
What I want is simply when I persist the object of EntityA it won't persist category, but instead it updates it's relationship with EntityA. After persisting the category_id of the second view should be 4 instead of 5.
I use entity manager's persist() method to persist the objects.
Technologies I use are jackson 2.0, Hibernate, Postgres as database.
I have also tested @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
annotation above both classes but it doesn't help.
What I'm doing wrong here? Any help is appreciated.