Hi all
I've got two classes: self -referencing ClassB and ClassA which works as a wrapper.
Code:
ClassA{
public void ClassA(String nr){
this.nr=nr
}
private String nr;
...
private Set<ClassB> pr;
...
}
ClassB{
private String ID;
private String nr;
private String parentID;
private Set<ClassB> pr ;
...
}
db structure (MySql5) as follows:
Code:
CREATE TABLE A (
Nr VARCHAR(20) NOT NULL,
PRIMARY KEY (Nr)
) ENGINE=InnoDB;
CREATE TABLE B (
ID VARCHAR(40) NOT NULL,
NrU VARCHAR(20)
ParentID VARCHAR(40),
PRIMARY KEY (ID)
) ENGINE=InnoDB;
and mapping:
Code:
<class name = "classA" table="A">
<id name="nr" type="string">
<column name="Nr"/>
<generator class="assigned"/>
</id>
<set name="pr" where="ParentID is null" cascade="all" lazy="false" >
<key column ="NrU" />
<one-to-many class="ClassB" />
</set>
</class>
<class name = "ClassB" table="B">
<id name="ID" type="string">
<column name="ID"/>
<generator class="guid"/>
</id>
<property name="nr" column="NrU" />
<property name="parentID" column="ParentID" not-null="false" />
<set cascade="all" lazy="false" name="pr" table="B" >
<key>
<column name="ParentID" not-null="true"/>
</key>
<one-to-many class="ClassB" />
</set>
</class>
I use Spring HibernateDaoSupport .There are no problems with persisting new objects of ClassA with embedded instances of ClassB. Data structure looks then as follows:
table A
Nr |
7777|
table B
ID|NrU|ParentID|
556886ea-11...|7777|null|
5568834a-11...|7777||556886ea-11...
5568814a-11...|7777||556884ea-11...
which is correct.
Trouble begins when there are no ClassB (table B) records and I try to update existing ClassA instance with new Set<ClassB>, eg
Code:
ClassA a = new ClassA("7777"); // I'm not retrieving this from db purposely
ClassB b = new ClassB("7777");
ClassB bb = new ClassB("7777");
b.getPr().add(bb);
a.getPr().add.(b);
getHibernateTemplate.saveOrUpdate(a);
after that database contains following records:
table B
table B
ID|NrU|ParentID|
556886ea-11...|7777|null|
5568834a-11...|null||556886ea-11...
5568814a-11...|null||556884ea-11...
There are missing NrU values in database. Only root contains NrU value, for other rows NrU == null.
Of course, when I retrieve existing ClassA from database and perform the same oerations, result is successfull.
Is there any way to perform such a update in a way I described ? Or maybe better take same other aproach ?
thanks