I have
one class
MyDirectory.java which is supposed to represent something like a usual directory.
Every directory might have several subdirectories.
I have
one database table
directories.
I'd like to create some objects of MyDirectory with one parent directory and a structure below, e.g.:
Code:
-parentDir
-childDir1
-childDir2
-childDir3
Finally I'd like to save all of them by using:
session.save(parentDir);
How is this possible (which mapping?)?
Is it possible without having to tell each childDir its parent?
Thanks a lot for your help!
Here is some code:
MyDirectory.javaCode:
package test;
import java.util.HashSet;
import java.util.Set;
public class MyDirectory {
private Long id;
private String name;
private Set subDirs = new HashSet();
public MyDirectory() {
}
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 Set getSubDirs() {
return subDirs;
}
public void setSubDirs(Set subDirs) {
this.subDirs = subDirs;
}
}
TestMyDirectory.javaCode:
[...]
MyDirectory parent = new MyDirectory();
parent.setName("AAA");
//create child directories
MyDirectory child1 = new MyDirectory();
child1.setName("BBB");
MyDirectory child2 = new MyDirectory();
child2.setName("CCC");
MyDirectory child3 = new MyDirectory();
child3.setName("DDD");
//add children to parent list
parent.getSubDirs().add(child1);
parent.getSubDirs().add(child2);
parent.getSubDirs().add(child3);
// save parent directory
session.save(parent);
session.flush();
[...]
MyDirectory.hbm.xmlCode:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class
name="test.MyDirectory"
table="directories"
>
<id
name="id"
column="id"
type="long"
>
<generator class="native"/>
</id>
<property
name="name"
type="string"
column="name"
/>
<set
name="subDirs"
table="directories"
lazy="false"
inverse="false"
cascade="all"
sort="unsorted"
>
<key
column="parent"
/>
<one-to-many
class="test.MyDirectory"
/>
</set>
</class>
</hibernate-mapping>
DatabaseCode:
CREATE TABLE directories (
id bigint(20) NOT NULL auto_increment,
name varchar(255) NOT NULL default '',
parent bigint(20) default '0',
PRIMARY KEY (id)
) TYPE=InnoDB;