index-1-1.jpg
  • Aurora Solutions

One To Many Using Annotation

In this article I am going to write about one to many relationship using annotation 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. 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

package com.hibernate.tutorial;

@Entity
@Table(name = "category")
public class Category implements java.io.Serializable{

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

@Id
    @GenericGenerator(name="generator", strategy="increment")
    @GeneratedValue(generator="generator")
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "name", unique = true, nullable = false)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "category")
    public Set getProductDetails() {
        return productDetails;
    }

    public void setProductDetail(Set productDetails) {
        this.productDetails = productDetails;
    }

 }

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

private Category category;

@ManyToOne
    @JoinColumn(name = "category_id", nullable = false)
    public Category getCategory() {
        return category;
    }
    public void setCategory(Category category) {
        this.category = category;

Step 3. Add following mapping line to Hibernate.cfg.xml file

<mapping class="com.hibernate.tutorial.Category"></mapping>

Step 4. 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 many-to-many relationship using XML’. I will look forward to your suggestions and questions in the comment section.

0 views0 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