index-1-1.jpg
  • Aurora Solutions

One To Many Relationship Using XML

In this article I am going to write about one to many relationship using XML in hibernate. One to many means that we can have only many rows in one table against one row in another table. In my previous article I created simple application which creates one table in database. In this article I will change that table and create a new table to describe one to many relationship. In previous article I created Product table and now we will create Category table to create one to many relationship. We will add a column to Product Table which will point to some row in category table.

Step 1. Add Category table and Column to Product table

-- Table: category
-- DROP TABLE category;
CREATE TABLE category
(
  id integer NOT NULL,
  name character varying,
  CONSTRAINT pk_category PRIMARY KEY (id )
)
WITH (
  OIDS=FALSE
);
ALTER TABLE category
  OWNER TO postgres;

ALTER TABLE product ADD COLUMN category_id character varying(50)
ADD CONSTRAINT fk_category FOREIGN KEY (category_id)
      REFERENCES category (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION;

Step 2. Create Hibernate Model Class

public class Category implements java.io.Serializable{

private Integer id;
private String name;
private Set productDetails = new HashSet();

    //constructor & getter and setter methods

}

Now add to product class variable of type Category class like this and add getter and setter method.

private Category category;

Step 3. Create/Modify Hibernate Mapping Files Create Category.hbm.xml to map category. Category.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Mar 22, 2014 8:13:50 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.hibernate.tutorial.Category" table="CATEGORY">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<set name="productDetails" table="PRODUCT" inverse="true" lazy="true" access="field" fetch="select">
<key>
<column name="ID" />
</key>
<one-to-many />
</set>
</class>
</hibernate-mapping>

Add following line to Product.hbm.xml we created in our previous article here.

<many-to-one name="category" fetch="select">
<column name="CATEGORY_ID" not-null="true"/>
</many-to-one>

Step 4. Add following mapping line to Hibernate.hbm.xml file

<mapping resource="com/hibernate/tutorial/Category.hbm.xml"/>

Step 5. Execute Test Cases

public class MainTest extends TestCase {
    private static Session session;
    private static Category category;
    private static Product product;

    @org.junit.Test
    public void testCategory(){
        String name = "Penalty";
        category = new Category();
        session = HibernatePersistence.getSessionFactory().openSession();
        category.setName(name);
        session.beginTransaction();

        Integer categoryId = (Integer) session.save(category);
        session.getTransaction().commit();
        category = (Category) session.get(Category.class, categoryId);

        assertEquals("Penalty", category.getName());
    }

    @org.junit.Test
    public void testProduct(){
        product = new Product();
        session = HibernatePersistence.getSessionFactory().openSession();
        product.setName("COKE");
        product.setCode("C002");
        product.setPrice(new BigDecimal("18.00"));
        product.setCategory(category);
        session.beginTransaction();

        Integer productId =(Integer) session.save(product);
        session.getTransaction().commit();
        product = (Product) session.get(Product.class, productId);

        assertEquals("COKE",product.getName());
        assertEquals(category.getId(), product.getCategory().getId());
    }

Hope this article will help you in learning the basics of Hibernate. In my next article I am going to write about ‘How to make one-to-many relationship using Annotation’. I will look forward to your suggestions and questions in the comment section.


Download Project

1 view0 comments

Recent Posts

See All

TRANSIENT FIELD WITH ANNOTATION VALIDATORS

Recently I got the chance to work with annotation validators @Pattern on transient field. Basically it was a password field which I had to validate first and then encrypt it and set it in another pers

Get and Load Methods in Hibernate

Both Get and Load methods in hibernate fetch row from databases. The functionality is similar but there is a difference between the way they work. hibernateSession.get() This method will return the re

Many To Many Relationship Using Annotations

This article is about how to write many to many relationships using annotations in hibernate. Many to many means that we can have many rows in one table against many rows in another table. Here is an