Hibernate List mapping annotation example



CodeJava
Coding Your Passion
  • Home>
  • Frameworks>
  • Hibernate
Learn Hibernate:

  • Learn Hibernate on YouTube

  • Hibernate Hello World for Beginner

  • Hibernate JPA Annotations Tutorial for Beginners

  • Hibernate Query Language Examples

  • Hibernate Enum Type Mapping

  • Hibernate Binary Data and BLOB Mapping

  • Java Hibernate Reverse Engineering Tutorial

  • Hibernate One-to-One With Primary Key XML Mapping

  • Hibernate One-to-One With Foreign Key XML Mapping

  • Hibernate One-to-One Mapping with Foreign Key Annotations

  • Hibernate One-to-One Association on Primary Key Annotations

  • Hibernate One-to-Many XML Mapping

  • Hibernate One-to-Many Association Annotations

  • Hibernate One-to-Many Association on Join Table Annotations

  • Hibernate One-to-Many Using Join Table XML Mapping

  • Hibernate Many-to-Many XML Mapping

  • Hibernate Many-to-Many Association Annotations

  • Hibernate Many-to-Many Association with Extra Columns in Join Table

  • How to use c3p0 with Hibernate

  • How to configure Proxool with Hibernate



Hibernate One-to-Many Association Annotations Example

DetailsWritten by Nam Ha MinhLast Updated on 15 May 2020 | Print Email


This Hibernate tutorial will take you go through an example of mapping a one-to-many association using JPA annotations - an alternative to XML descriptor approach which is described in the Hibernate One-to-Many XML Mapping Example tutorial.Lets look at the following entity relationship diagram to recall about the one-to-many association:
Here, the multiplicity between the two entities category and product is one-to-many, meaning that a category can have one or many products. This one-to-many association is constrained by the foreign key in the product table.The following software programs and libraries are used in order to develop a sample Hibernate application that implements the one-to-many association above [you can use newer versions]:
  • Hibernate 4.2.7.SP1
  • JDK 7
  • Eclipse IDE 4.3 [Kepler]
  • Maven 3
  • MySQL Community Server 5.5.23
  • MySQL Connector Java driver 5.1.26
Of course you can use similar versions. Heres the summary of steps which we are going to follow:Table of content:
  1. Creating Database and Tables
  2. Creating Maven-Eclipse Project
  3. Annotating Model Classes for One-to-Many Association
  4. Writing Hibernate Configuration File
  5. Writing a Test Program

1. Creating Database and Tables

Execute the following MySQL script to create a database stockdb and two tables category and product:create database stockdb; use stockdb; CREATE TABLE `category` [ `category_id` int[11] NOT NULL AUTO_INCREMENT, `name` varchar[45] NOT NULL, PRIMARY KEY [`category_id`] ]; CREATE TABLE `product` [ `product_id` int[11] NOT NULL AUTO_INCREMENT, `name` varchar[45] NOT NULL, `description` varchar[512] NOT NULL, `price` float NOT NULL, `category_id` int[11] NOT NULL, PRIMARY KEY [`product_id`], KEY `fk_category` [`category_id`], CONSTRAINT `fk_category` FOREIGN KEY [`category_id`] REFERENCES `category` [`category_id`] ];


The structure of the stockdb database would look like this:


2. Creating Maven-Eclipse Project

In Eclipse IDE, create a Maven project named HibernateOne2ManyAnnotationsExample with the following structure:
This project consists of the following files:
  • Model classes: Category.java and Product.java
  • Hibernate XML configuration file: hibernate.cfg.xml
  • Test program: StockManager.java
  • Maven project: pom.xml
Note that when using annotations approach, the XML mapping files for the model classes are no longer needed. For JAR files of Hibernate and MySQL Connector/J, update the pom.xml file as follows: 4.0.0 net.codejava.hibernate HibernateOne2ManyAnnotationsExample 1.0 Example of a Hibernate one-to-many association mapping using annotations org.hibernate hibernate-core 4.2.7.SP1 mysql mysql-connector-java 5.1.26 And Maven will resolve related dependencies if any.


3. Annotating Model Classes for One-to-Many Association

Create two model classes called Category.java and Product.java with the following source code:File net\codejava\hibernate\Category.java:package net.codejava.hibernate; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table[name = "CATEGORY"] public class Category { private long id; private String name; private Set products; public Category[] { } public Category[String name] { this.name = name; } @Id @Column[name = "CATEGORY_ID"] @GeneratedValue public long getId[] { return id; } @OneToMany[mappedBy = "category", cascade = CascadeType.ALL] public Set getProducts[] { return products; } // other getters and setters... }File net\codejava\hibernate\Product.java:package net.codejava.hibernate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table[name = "PRODUCT"] public class Product { private long id; private String name; private String description; private float price; private Category category; public Product[] { } public Product[String name, String description, float price, Category category] { this.name = name; this.description = description; this.price = price; this.category = category; } @Id @Column[name = "PRODUCT_ID"] @GeneratedValue public long getId[] { return id; } @ManyToOne @JoinColumn[name = "CATEGORY_ID"] public Category getCategory[] { return category; } // other getters and setters... }Note that, the Category class has a set of Products, and the Product has a reference back to the Category.And, as we can see, only JPA annotations are used to annotate the model classes. The @Entity, @Table, @Column, @Id and @GeneratedValue annotations are self-explanatory and easy to understand. They are the basic elements needed for annotating any entities in Hibernate, regardless of the association. We pay attention to the annotations that make the one-to-many association: @OneToMany, @ManyToOne and @JoinColumn. Lets look at the code closely:
  • In the Category side:private Set products; @OneToMany[mappedBy = "category", cascade = CascadeType.ALL] public Set getProducts[] { return products; }Here, the mappedBy attribute is mandatory, as it specifies that the one-to-many association is mapped by this side [Category]; and the cascade attribute make sure Hibernate will save/update the products set when saving/updating this category.
  • In the Product side:private Category category; @ManyToOne @JoinColumn[name = "CATEGORY_ID"] public Category getCategory[] { return category; }Here, the @JoinColumn annotation specifies the join column of the association. It is also mandatory.
Therefore, remember the key annotations are used for mapping a one-to-many association: @OneToMany, @ManyToOne and @JoinColumn.


4. Writing Hibernate Configuration File

Configure database connection settings and mapping classes in the hibernate.cfg.xml file as follows: com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/stockdb root secret org.hibernate.dialect.MySQLDialect true


5. Writing a Test Program

So far we have finished the configuration part. Now, lets write a test program [StockManager.java] with the following source code:package net.codejava.hibernate; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; /** * * This program demonstrates using JPA annotations in Hibernate * in order to implement a one-to-many association mapping. * @author www.codejava.net * */ public class StockManager { public static void main[String[] args] { // loads configuration and mappings Configuration configuration = new Configuration[].configure[]; ServiceRegistryBuilder registry = new ServiceRegistryBuilder[]; registry.applySettings[configuration.getProperties[]]; ServiceRegistry serviceRegistry = registry.buildServiceRegistry[]; // builds a session factory from the service registry SessionFactory sessionFactory = configuration.buildSessionFactory[serviceRegistry]; // obtains the session Session session = sessionFactory.openSession[]; session.beginTransaction[]; Category category = new Category["Computer"]; Product pc = new Product["DELL PC", "Quad-core PC", 1200, category]; Product laptop = new Product["MacBook", "Apple High-end laptop", 2100, category]; Product phone = new Product["iPhone 5", "Apple Best-selling smartphone", 499, category]; Product tablet = new Product["iPad 3", "Apple Best-selling tablet", 1099, category]; Set products = new HashSet[]; products.add[pc]; products.add[laptop]; products.add[phone]; products.add[tablet]; category.setProducts[products]; session.save[category]; session.getTransaction[].commit[]; session.close[]; } }Output of the program:Hibernate: insert into CATEGORY [name] values [?] Hibernate: insert into PRODUCT [CATEGORY_ID, description, name, price] values [?, ?, ?, ?] Hibernate: insert into PRODUCT [CATEGORY_ID, description, name, price] values [?, ?, ?, ?] Hibernate: insert into PRODUCT [CATEGORY_ID, description, name, price] values [?, ?, ?, ?] Hibernate: insert into PRODUCT [CATEGORY_ID, description, name, price] values [?, ?, ?, ?]Result in the category table:
Result in the product table:
You can also learn by following this video:

Related Hibernate One-to-Many Tutorials:

  • Hibernate One-to-Many Association on Join Table Annotations Example
  • Hibernate One-to-Many Using Join Table XML Mapping Example
  • Hibernate One-to-Many XML Mapping Example

Other Hibernate Tutorials:

  • Java Hibernate JPA Annotations Tutorial for Beginners
  • Hibernate Hello World Tutorial for Beginners with Eclipse and MySQL
  • Hibernate One-to-One Association on Primary Key Annotations Example
  • Hibernate Many-to-Many Association with Extra Columns in Join Table Example
  • Hibernate Enum Type Mapping Example
  • Hibernate Binary Data and BLOB Mapping Example
  • Hibernate Query Language [HQL] Example
  • Java Hibernate Reverse Engineering Tutorial with Eclipse and MySQL
  • Hibernate Basics - 3 ways to delete an entity from the datastore

About the Author:

Nam Ha Minh is certified Java programmer [SCJP and SCWCD]. He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
HibernarteOne2ManyAnnotationsExample.zip
[Eclipse-Maven project]17 kB

Add comment

Notify me of follow-up comments

Send
Cancel

Comments

123
#11Alejandro Barrero2018-08-29 09:11
StockManager doesn't work; i am getting
Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml
Actually you didn't specify where to put it.
Quote
#10amitabh2018-06-14 09:18
Cont....

Category table:
Category_id Category_Name
1 Foods
2 Foods

Product table:
product_id category_id product_name
101 1 vegitable
102 2 Processed foods

So now how to map so that if category_name is Food it do not insert another row as food again and i can have multiple products under one category?
Quote
#9amitabh2018-06-14 09:12
One question here , There is one scenario where i used ur example, so for the first time i insert category_name as Foods [Category_id = 1] with product as vegitables. so it will insert first in category and then persist vegitable into product along with category id.
Now, i want add one more product [Processed foods] under same category [Food] but in this case it created one more category_id =2 it do not refer the exiting category and insert in product table as
Quote
#8Jervy2017-06-24 09:09
Im having problem with ServiceRegistryBuilder class. it seems that I need another libraries. what should I do?
Quote
#7Amin2017-04-09 01:49
How to get user input with your project where details form take more then 5 Products. Can you Help Me Sir.


Amin
Quote
123
Refresh comments list

Video liên quan

Chủ Đề