JPA 2.0 provider hibernation

I have a very strange problem: we use jpa 2.0 with hibernate annotations. The database created through JPA DDL is true, and MySQL is the database;

I will provide some reference classes and then my logo.

@MappedSuperclass public abstract class Common implements serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false) private Long id; @ManyToOne @JoinColumn private Address address; //with all getter and setters //as well equal and hashCode } @Entity public class Parent extends Common{ private String name; @OneToMany(cascade = {CascadeType.MERGE,CascadeType.PERSIST}, mappedBy = "parent") private List<Child> child; //setters and rest of class } @Entity public class Child extends Common{ //some properties with getter/setters } @Entity public class Address implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false) private Long id; private String street; //rest of class with get/setter } 

as in the code, you can see that the parents and child classes extend the common class, so that both have a property and an address identifier, the problem occurs when the referentiality of addresses in the parent class changes, which reflects the same change in all the child objects in the list, and if the refference change address in the child class, then when merging, it will also change the parent's address expression

I can not understand, this is jpa or hibernate problem

+6
java java-ee hibernate jpa
source share
1 answer

If you have shared instances of the address, the changes made when it in the "scope" of the child affects the parent because you are dealing with the same instance of the address in the parent.

For example:

 Parent1.address => Address #1 Child1.address => Address #2 Child2.address => Address #2 Child3.address => Address #1 

In this case, if you change Child3.address.street, it means that he also changed Parent1.address.street. Note that what makes Address in Parent1 and Child3 the same is an identifier. If they contain the same identifier, they represent the same instance (that is, "shared" between both objects).

+1
source share

All Articles