Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 263
Rooh Avatar asked Dec 30 '10 08:12

Rooh


1 Answers

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).

like image 188
jpkrohling Avatar answered Oct 21 '22 14:10

jpkrohling