Home Hibernate Hibernaterelationships Hibernate One-to-many Relationships



Hibernate One-to-many Relationships
Posted on: January 28, 2010 at 12:00 AM
Here you will learn one-to-many relationships developed using the hmb.xml file.

Hibernate One-to-many Relationships

     

Hibernate One-to-many Relationships - One to many example code in Hibernate using the xml file as metadata.

Here you will learn one-to-many relationships developed using the hmb.xml file. The one-to-many tag is used to define the relationships.

One-to-Many Relationships

In case of one-to-many relationships, each row in table A linked to multiple rows in table B. Here we will implement one-to-many relationship between two entries Group and Story. There exists multiple stories under a group.

We are using two tables grouptable and story and java entities Group and Story maps respectively. Here is the ER diagram

Java Persistence Objects:

The code for Group.java is given below:


package roseindia;

import java.util.List;


public class Group {
  
  private int id;
  private String name;
  private List stories;

  public Group(){
  }

  public Group(String name) {
  this.name = name;
  }

  public void setId(int i) {
  id = i;
  }

  public int getId() {
  return id;
  }

  public void setName(String n) {
  name = n;
  }

  public String getName() {
  return name;
  }

  public void setStories(List sl) {
  stories = sl;
  }

  public List getStories() {
  return stories;
  }

}

The code for Story.java is given below:

package roseindia;

public class Story {
  
  private int id;
  private String info;
  private Group group;

  public Story(){
  }

  public Group getGroup() {
  return group;
  }

  public void setGroup(Group group) {
  this.group = group;
  }

  public Story(String info) {
  this.info = info;
  }

  public void setId(int i) {
  id = i;
  }

  public int getId() {
  return id;
  }

  public void setInfo(String n) {
  info = n;
  }

  public String getInfo() {
  return info;
  }

}

Mapping xml file (Group.hbm.xml):

This file contains the mapping for both the entities Stroy and Group which maps with the tables gropuptable and story respectively.

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="roseindia.Group" table="gropuptable">

<id name="id" type="int" column="id">

<generator class="native" />

</id>

<property name="name" type="java.lang.String" column="name"

length="50" />

<list name="stories" cascade="all">

<key column="parent_id" />

<index column="idx" />

<one-to-many class="roseindia.Story" />

</list>

</class>

<class name="roseindia.Story" table="story">

<id name="id" type="int" column="id">

<generator class="increment" />

</id>

<property name="info" type="java.lang.String" column="info"

length="255" />

<many-to-one name="group" class="roseindia.Group" column="parent_id" />

</class>

</hibernate-mapping>

 

 

The following mapping tag defines the one-to-many mapping between Group and Story entities.

<list name="stories" cascade="all">

<key column="parent_id" />

<index column="idx" />

<one-to-many class="roseindia.Story" />

</list>

In Group.java we have stories variable of the list type, so we have used the <list../> tag here. The <one-to-many ../> specifies the one to many relationships to Story entity.

Running the Program:

To run and test the program you have to execute the OneToManyRelation.java. Here is the full code of OneToManyRelation.java file:

 

package roseindia;

import java.awt.Stroke;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

//Goups and Stories

public class OneToManyRelation {

  // Group and Multiple Stories

  public static void main(String[] args) {

  SessionFactory sessFact = null;
  Session session = null;
  try {
  sessFact = new Configuration().configure()
   .buildSessionFactory
();
  session = sessFact.openSession();
  Transaction tr = session.beginTransaction();

  // Group Object
  Group group = new Group("Java Group 2");
  // Array list to hold stories
  ArrayList list = new ArrayList();

  // Create Stories
  Story javaHistory = new Story();
  javaHistory.setInfo("Java History");
  list.add(javaHistory);

  // Create Stories
  Story javaPlatform = new Story();
  javaPlatform.setInfo("Java Platforms");
  list.add(javaPlatform);

  // Create Stories
  Story javaNews = new Story();
  javaNews.setInfo("Java News");
  list.add(javaNews);

  // Create Stories
  Story jeeNews = new Story();
  jeeNews.setInfo("JEE News");
  list.add(jeeNews);

  // Add the list to Group object
  group.setStories(list);

  // Save group
  session.save(group);

  // Print the generated group id
  System.out.println("Group id:" 
  group.getId
());

  /*
 
 * //Load the group class Group g = (Group)
 * session.load(Group.class, 1); 
   System.out.println("Group Name:" +

 * g.getName());
 
 * List listStories = g.getStories();
    Iterator storiesIter =

 * listStories.iterator(); 
   while(storiesIter.hasNext()) { Story

 * story = (Story)storiesIter.next();
 * System.out.println("Story Info:" + 
   story.getInfo()); }

 */

  tr.commit();

  catch (HibernateException he) {
  System.out.println(he.getMessage());
  finally {
  // Session close
  session.close();
  // SessionFactory close
  sessFact.close();
  }

  }

}

The above code is self explanatory, we are creating the objects of Group:

  // Group Object
  Group group = new Group("Java Group 2");

Then set the author name:

 

 

The create ArrayList object set and add many Story objects:

// Array list to hold stories

ArrayList list = new ArrayList();

// Create Stories

Story javaHistory = new Story();

javaHistory.setInfo("Java History");

list.add(javaHistory);

// Create Stories

Story javaPlatform = new Story();

javaPlatform.setInfo("Java Platforms");

list.add(javaPlatform);

// Create Stories

Story javaNews = new Story();

javaNews.setInfo("Java News");

list.add(javaNews);

// Create Stories

Story jeeNews = new Story();

jeeNews.setInfo("JEE News");

list.add(jeeNews);

 

 

Finally add the book set to the group object and save the group object:

// Add the list to Group object

group.setStories(list);

// Save group

session.save(group);

 

 

Here is output of the program when executed in Eclipse IDE.

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: insert into gropuptable (name) values (?)

Hibernate: select max(id) from story

Group id:2

Hibernate: insert into story (info, parent_id, id) values (?, ?, ?)

Hibernate: insert into story (info, parent_id, id) values (?, ?, ?)

Hibernate: insert into story (info, parent_id, id) values (?, ?, ?)

Hibernate: insert into story (info, parent_id, id) values (?, ?, ?)

Hibernate: update story set parent_id=?, idx=? where id=?

Hibernate: update story set parent_id=?, idx=? where id=?

Hibernate: update story set parent_id=?, idx=? where id=?

Hibernate: update story set parent_id=?, idx=? where id=?

 

In this section we learned about the one-to-many relationships in Hibernate.

In next section we will learn how to create and run the many-to-many mapping in Hibernate. Many to many relationships is interesting as one extra table is needed to persist the relationship.

Download the code example

Related Tags for Hibernate One-to-many Relationships:


More Tutorials from this section

Ask Questions?    Discuss: Hibernate One-to-many Relationships   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.