Sorry for my bad english :o)
First class
Code:
package testcascade;
import java.io.Serializable;
import javax.persistence.*;
@Entity(access=AccessType.FIELD)
@Table(name="CHILD")
public class Child {
@Id(generate=GeneratorType.AUTO)
protected Long id;
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
@ManyToOne(cascade=CascadeType.PERSIST, fetch=FetchType.LAZY)
protected Parent p;
public Parent getParent(){return p;}
public void setParent(Parent p) { this.p = p; }
}
second class
Code:
package testcascade;
import javax.persistence.*;
@Entity(access=AccessType.FIELD)
@Table(name="PARENT")
public class Parent{
@Id(generate=GeneratorType.AUTO)
protected Long id;
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
}
test class
Code:
package testcascade;
import org.hibernate.*;
import test.HibernateUtil2;
public class TestCascade {
public static void main(String[] args) {
Parent p = new Parent();
Child c = new Child();
c.setParent(p);
Session s = HibernateUtil2.currentSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(c);
tx.commit();
tx = s.beginTransaction();
s.delete(c);
tx.commit();
HibernateUtil2.closeSession();
}
}
Create Child, create Parent, set Parent to Child, save Child. Parent also should be saved because CascadeType.PERSIST.
But sql-log is INSERT INTO CHILD VALUES(1,NULL) and exception throws
Code:
Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: testcascade.Parent
Looks like PERSIST (and other cascade types but ALL doesn't work).
When I set CascadeType.ALL - it works fine. But when delete Child - parent also delete (ALL :o)) I don't want this.
But if replace ALL with {MERGE, REFRESH, REMOVE, PERSIST} - same sql query and exception!
I use latest
hibernate-3.1.rc1.jar
hibernate-annotations-3.1beta5.jar
ejb3-persistence-1.0.jar
Help! :o)