@Entity
@Table(name = "parent")
public final class Parent extends Base {
@OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Person person;
and doing (amongst other things) this :
Parent parent = new Parent();
Person person = new Person();
parent.setPerson(person);
session.save(parent);
I get the mentioned exception ?
Do I manually need to call session.save(person) before ? do I have to add a cascade type annotation to the childs class definition(where it references the parent) ?
Or have I missed something else obvious ?
I don't want to use CascadeType.ALL as when a parent is deleted I want to keep the person(child).
Both entities/tables extend a common Base table :
@MappedSuperclass()
public abstract class Base {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
public Integer getId() {
return id;
}
Will this effect which cascade type is required ?
Best Answer
You haven't mentioned the Hibernate version, but this hasn't changed since I ever started using it.
As you can read in the Hibernate reference, to get the Java standard
SAVE_UPDATE
you need{CascadeType.PERSIST, CascadeType.MERGE}
in Hibernate.EDIT: Seeing the updated info, what you're doing now causes Hibernate to treat it as a bi-directional one-to-one mapping. This basically means that for each object in any of those two tables, there has got to be a counterpart in the other table with the same ID. Therefore, you cannot delete only one of them, you would lose FK integrity.
If you want it to be a unidirectional mapping, e.g., if you want to be able to delete the person but leave the parent -- you have to specify a FK, usually via
@JoinColumn
, like@JoinColumn(name="PERSON_ID", unique=false, nullable=true, insertable=true, updatable=true)