I'm trying to set up a parent-child relationship, where parent might not always exist in the DB at the time of saving. I'm trying to set it up in the way that, when A is being saved, if the appropriate B already exist in the DB, its state would be updated; if referenced B doesn't exist, a new one would be inserted before inserting / updating A. Is it at all possible, and am I doing it the right way?
Hibernate version: 3.0.5
Mapping documents:
Code:
<class name="A" table="A">
<id name="id" column="id" unsaved-value="null">
<generator class="native">
<param name="sequence">sq_a</param>
</generator>
</id>
<many-to-one name="b" column="b_id" class="B" not-null="true" insert="false"
update="false" cascade="all" lazy="false" />
<!-- "scac" property has to be available from A directly -->
<property name="scac" column="b_id" />
</class>
<class name="B" table="B">
<id name="scac" column="id" unsaved-value="null">
<generator class="assigned" />
</id>
<property name="data" column="name" />
</class>
Model codeCode between sessionFactory.openSession() and session.close():Code:
A a = new A();
a.setScac("STVU");
B b = new B();
b.setScac("STVU");
b.setData("Bar");
a.setB(b);
dao.save(a);
Name and version of the database you are using: Oracle 8.1.7
Code:
CREATE TABLE B (
ID VARCHAR2 (6) NOT NULL,
NAME VARCHAR2 (20),
CONSTRAINT PK_B
PRIMARY KEY ( ID ) ) ;
CREATE TABLE A (
ID NUMBER NOT NULL,
B_ID VARCHAR2 (6) NOT NULL,
CONSTRAINT PK_A
PRIMARY KEY ( ID ) ) ;
ALTER TABLE A ADD CONSTRAINT FK_B_A
FOREIGN KEY (B_ID)
REFERENCES B (ID) ON DELETE CASCADE;
The generated SQL (show_sql=true):Code:
DEBUG - select sq_a.nextval from dual
DEBUG - insert into A (b_id, id) values (?, ?)
Debug level Hibernate log excerpt:Code:
log4j.logger.org.hibernate.SQL=debug
Code:
public class A {
private Integer id;
private String scac;
private B b;
public String getScac() {
return scac;
}
public void setScac(String foo) {
this.scac = foo;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public B getB() {
return b;
}
public void setB(B bs) {
this.b = bs;
}
}
public class B {
private String scac;
private String data;
public String getScac() {
return scac;
}
public void setScac(String id) {
this.scac = id;
}
public String getData() {
return data;
}
public void setData(String bar) {
this.data = bar;
}
}