I am trying to establish unidirectional relationship between two entities called Person and Address,while saving Person(containing collection of Address) getting org.hibernate.TransientObjectException: object references an unsaved transient instance.
When I change cascadeType=all,child objects are getting propagated.But the problem here is with cascadeType=all Hibernate also tries to delete child entities on Deleting Owning entity.I don't want that to happen because in ManyToMany relationship child entity might be being referenced by some other entity.Ideally cascadeType=persist should do the job but unfortunately that give me mentioned exception.
Can somebody help me out how can I save the child objects (Address) with cascadeType=persist.I just wonder why cascadeType=persist is not doing the task of persisting.
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE})
private Collection<Address> address=new HashSet<Address>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Address> getAddress() {
return address;
}
public void setAddress(Collection<Address> address) {
this.address = address;
}
}
@Entity(name="Address")
public class Address {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;
@Column(name="country")
private String country;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}