` Hibernate One To Many Mapping With Annotation Tutorial With Example | Java2Study.com

Hibernate One To Many Mapping With Annotation Tutorial With Example

In Previous Tutorial we have seen Hibernate One TO Many XML Mapping.In This Tutorial We Will Learn Hibernate One To Many Mapping With Annotation.

Definition:

            "One To Many Mapping occurs when one entity object is related to many objects of another              entity."
That Means one record of one Table is related to many rows of another Table In Database.
For Example One Movie is having Many Actors.
Let Us See An Example For Hibernate One To Many Mapping With Annotation
Database Table Design
The Following Diagram is One To Many Table Design.In Database Create Following Two Tables.According Diagram One Movie is having Association on Many Actors.



/*Create Table movie

CREATE TABLE `movie` (
  `movie_id` int(11) NOT NULL,
  `movie_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`movie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

 
/*Create Table actors

CREATE TABLE `actors` (
  `actor_id` int(11) NOT NULL,
  `actor_name` varchar(255) DEFAULT NULL,
  `movie_id` int(11) NOT NULL,
  PRIMARY KEY (`actor_id`),
  KEY `FKAB2F951E6F3463B8` (`movie_id`),
  CONSTRAINT `FKAB2F951E6F3463B8` FOREIGN KEY (`movie_id`) REFERENCES `movie` (`movie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1




Project Structure:



















Maven Dependencies
File:pom.xml
pom.xml contains Dependencies For Hibernate And MySql And JPA
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelversion>4.0.0</modelversion>
  <groupid>HibernateOneToManyAnnotation</groupid>
  <artifactid>HibernateOneToManyAnnotation</artifactid>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
  <dependency>
 <groupid>org.hibernate</groupid>
 <artifactid>hibernate-core</artifactid>
 <version>3.6.7.Final</version>
</dependency>

<dependency>
 <groupid>mysql</groupid>
 <artifactid>mysql-connector-java</artifactid>
 <version>5.1.37</version>
</dependency>
<dependency>
 <groupid>antlr</groupid>
 <artifactid>antlr</artifactid>
 <version>2.7.6</version>
</dependency>
<dependency>
 <groupid>org.hibernate.javax.persistence</groupid>
 <artifactid>hibernate-jpa-2.0-api</artifactid>
 <version>1.0.1.Final</version>
</dependency>

<dependency>
 <groupid>dom4j</groupid>
 <artifactid>dom4j</artifactid>
 <version>1.6.1</version>
    <exclusions>
     <exclusion>
      <artifactid>xml-apis</artifactid>
      <groupid>xml-apis</groupid>
     </exclusion>
    </exclusions>
</dependency>
<dependency>
 <groupid>javassist</groupid>
 <artifactid>javassist</artifactid>
 <version>3.10.0.GA</version>
</dependency>

<dependency>
 <groupid>commons-collections</groupid>
 <artifactid>commons-collections</artifactid>
 <version>3.1</version>
</dependency>
<dependency>
 <groupid>javax.transaction</groupid>
 <artifactid>jta</artifactid>
 <version>1.1</version>
</dependency>
<dependency>
 <groupid>org.hibernate</groupid>
 <artifactid>hibernate-commons-annotations</artifactid>
 <version>3.2.0.Final</version>
</dependency>
<dependency>
 <groupid>org.slf4j</groupid>
 <artifactid>slf4j-api</artifactid>
 <version>1.6.1</version>
</dependency>

<dependency>
 <groupid>commons-logging</groupid>
 <artifactid>commons-logging</artifactid>
 <version>1.2</version>
</dependency>
</dependencies>
</project>


Hibernate Model Classes
File:Movie.java
package com.javalschool.model;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "movie")
public class Movie {
 @Id
 @Column(name="movie_id", nullable = false)
 private int movieId;
 @Column(name="movie_name")
 private String movieName;
 @OneToMany(targetEntity=Actors.class,cascade=CascadeType.ALL)
 @JoinColumn(name="movie_id", nullable = false)
 private Set actors;
 public int getMovieId() {
  return movieId;
 }
 public void setMovieId(int movieId) {
  this.movieId = movieId;
 }
 public String getMovieName() {
  return movieName;
 }
 public void setMovieName(String movieName) {
  this.movieName = movieName;
 }
 public Set getActors() {
  return actors;
 }
 public void setActors(Set actors) {
  this.actors = actors;
 }
 

}

The Following Two Annotations will Represent The One To Many Mapping
@OneToMany
@JoinColumn

File:Actors.java
package com.javalschool.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "actors")
public class Actors {
 @Id
 @Column(name = "actor_id")
 private int actorId;
 @Column(name = "actor_name")
 private String actorName;

 public int getActorId() {
  return actorId;
 }

 public void setActorId(int actorId) {
  this.actorId = actorId;
 }

 public String getActorName() {
  return actorName;
 }

 public void setActorName(String actorName) {
  this.actorName = actorName;
 }

}


Hibernate Configuration File
File:hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<lt!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root123</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <property name="show_sql">true</property>
    <mapping class="com.javalschool.model.Movie">
    <mapping class="com.javalschool.model.Actors">
</mapping></mapping></session-factory>
</hibernate-configuration>
Now Create The Test class And Run The Application
File:Test.java
package com.javalschool.test;

import java.util.HashSet;

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

import com.javalschool.model.Actors;

import com.javalschool.model.Movie;


public class Test {

 public static void main(String[] args) {
      Configuration configuration = new Configuration();
      configuration.configure();
      SessionFactory sessionFactory = configuration.buildSessionFactory();
      Session session = sessionFactory.openSession();
      Transaction transaction= session.beginTransaction();
      
      Movie movie = new Movie();
      movie.setMovieId(987);
      movie.setMovieName("ABC");
      
      Actors actor = new Actors();
      actor.setActorId(983);
      actor.setActorName("xyz");
      
      Actors actor1 = new Actors();
      actor1.setActorId(389);
      actor1.setActorName("AAA");
      
      
      Actors actor2 = new Actors();
      actor2.setActorId(76);
      actor2.setActorName("BBB");
     
      
      HashSet hashset = new HashSet();
      hashset.add(actor);
      hashset.add(actor1);
      hashset.add(actor2);
      
      movie.setActors(hashset);
      session.save(movie);
      session.save(actor);
      session.save(actor1);
      session.save(actor2);
      transaction.commit();
      session.close();
      sessionFactory.close();
      
      
 }

}

output


Movie Table





Actors Table