简体   繁体   中英

JPA 2.0 Provider Hibernate

I have very strange problem we are using jpa 2.0 with hibernate annotations based Database generated through JPA DDL is true and MySQL as Database;

i will provide some reference classes and then my porblem.

@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 code you can see that parents and child classes extends Common class so both have address property and id , the problem occurs when change the address refference in parent class it reflect same change in all child objects in list and if change address refference in child class then on merge it will change address refference of parent as well

i am not able to figure out is it is problem of jpa or hibernate

If you have shared instances of Address, changes made when it's in the "scope" of a child does affects the parent, because you are dealing with the same Address instance in the parent object.

For instance:

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 it also changed Parent1.address.street. Note that what makes Address in Parent1 and Child3 the same is the ID. If they hold the same ID, they are the same instance (ie: "shared" among both objects).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM