Hibernate one-to-many Example

From Javapedia

Jump to: navigation, search

Here are the example Java classes:

public class Parent {

 private long id;
 private Set<Child> children;
 public long getId() { return id; }
 public void setId(long id) { this.id = id; }
 public Set<Child> getChildren() { return children; }
 public void setChildren(Set<Child>) { this.children = children; }

}

public class Child {

 private long id;
 public long getId() { return id; }
 public void setId(long id) { this.id = id; }

}

The database tables would look like the following:

PARENT_TABLE ID BIGINT

CHILD_TABLE


ID BIGINT PARENT_ID BIGINT

Child.

The following files are the Hibernate mapping files. Take special note of the <one-to-many> inside of the "children" <set>.

Parent.hbm.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping>

 <class name="org.applabs.base.User" table="USER"> 
   <id column="USER_ID" name="id" type="java.lang.Long"> 
     <generator class="org.hibernate.id.TableHiLoGenerator"> 
       <param name="table">idgen</param>
       <param name="column">NEXT</param> 
     </generator> 
   </id> 
   <set name="children" inverse="true">
      <key column="parent_id"/>
      <one-to-many class="Child"/>
  </set>
 </class> 

</hibernate-mapping>

Child.hbm.xml


To add a child, use the following code:

Parent p = (Parent) session.load(Parent.class, pid); Child c = new Child(); c.setParent(p); p.getChildren().add(c); session.save(c); session.flush();

Only one SQL INSERT statement will be performed on the database.

Personal tools