Hibernate
Hibernate: One-TO-Many Relationship
In one-to-many mapping one entity is associated with multiple instances of another entity. It is mostly used to model a parent-child or master-detail relationship in a database. You can create a one-to-many mapping in Hibernate using the @OneToMany annotation. Typically, this is implemented using collections, such as a set or list, to represent the more than one side of the relationship within the one side of another entity.
For example, suppose we have two entities: Question and Answer. Each Question can have multiple Answers, but each Answers belongs to only one Question.
Lets understand this using below code example.
1: Create a Maven Project as below groupId is com.hiber.onetomanyhiber & artifactId is OnetoMany
2: Create two entity class Question & Answer for one-to-many mapping where one question have multiple Answer.
3: Create a database in mysql( I am using mysql here) by the name of onetomanydb
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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>com.hiber.onetomanyhiber</groupId>
<artifactId>OnetoMany</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>OnetoMany</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.6.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
</project>
hibernate.cfg.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/onetomanydb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name = "dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="com.hiber.onetomanyhiber.Question"/>
<mapping class="com.hiber.onetomanyhiber.Answer"/>
</session-factory>
</hibernate-configuration>
Question.java
package com.hiber.onetomanyhiber;
import java.util.List;
import javax.persistence.*;
@Entity
public class Question {
@Id
@Column(name="question_id")
int questionId;
String question;
@OneToMany(mappedBy = "question")
List<Answer> answers;
public Question() {
super();
// TODO Auto-generated constructor stub
}
public Question(int questionId, String question, List<Answer> answers) {
super();
this.questionId = questionId;
this.question = question;
this.answers = answers;
}
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
@Override
public String toString() {
return "Question [questionId=" + questionId + ", question=" + question + ", answers=" + answers + "]";
}
}
Answer.java
package com.hiber.onetomanyhiber;
import javax.persistence.*;
@Entity
public class Answer {
@Id
int answerid;
String answer;
@ManyToOne
Question question;
public Answer() {
super();
// TODO Auto-generated constructor stub
}
public Answer(int answerid, String answer) {
super();
this.answerid = answerid;
this.answer = answer;
}
public int getAnswerid() {
return answerid;
}
public void setAnswerid(int answerid) {
this.answerid = answerid;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
@Override
public String toString() {
return "Answer [answerid=" + answerid + ", answer=" + answer + "]";
}
}
App.java
package com.hiber.onetomanyhiber;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Question question1=new Question();
question1.setQuestionId(101);
question1.setQuestion("What is Java");
Answer question1ans1=new Answer();
question1ans1.setAnswerid(1);
question1ans1.setAnswer("Java is a programming language");
question1ans1.setQuestion(question1);
Answer question1ans2=new Answer();
question1ans2.setAnswerid(2);
question1ans2.setAnswer("Java is pure Object oriented language");
question1ans2.setQuestion(question1);
Answer question1ans3=new Answer();
question1ans3.setAnswerid(3);
question1ans3.setAnswer("Java is a High level language");
question1ans3.setQuestion(question1);
//---
Question question2=new Question();
question2.setQuestion("What is React JS");
question2.setQuestionId(201);
Answer question2ans1 =new Answer();
question2ans1.setAnswerid(4);
question2ans1.setAnswer("React is a open source developed by Facebook");
question2ans1.setQuestion(question2);
Answer question2ans2=new Answer();
question2ans2.setAnswerid(5);
question2ans2.setAnswer("React is a JAvascript Library");
question2ans2.setQuestion(question2);
Answer question2ans3=new Answer();
question2ans3.setAnswerid(6);
question2ans3.setAnswer("React is used for SPA");
question2ans3.setQuestion(question2);
List<Answer> ansList1=new ArrayList<Answer>();
ansList1.add(question1ans1);
ansList1.add(question1ans2);
ansList1.add(question1ans3);
question1.setAnswers(ansList1);
List<Answer> ansList2=new ArrayList<Answer>();
ansList2.add(question2ans1);
ansList2.add(question2ans2);
ansList2.add(question2ans3);
question2.setAnswers(ansList2);
Session session = factory.openSession();
Transaction transaction = session.beginTransaction();
session.save(question1);
session.save(question1ans1);
session.save(question1ans2);
session.save(question1ans3);
session.save(question2);
session.save(question2ans1);
session.save(question2ans2);
session.save(question2ans3);
transaction.commit();
session.close();
}
}
Output
mysql> show tables;
+-----------------------+
| Tables_in_onetomanydb |
+-----------------------+
| answer |
| question |
+-----------------------+
2 rows in set (0.00 sec)
mysql> select * from question;
+-------------+------------------+
| question_id | question |
+-------------+------------------+
| 101 | What is Java |
| 201 | What is React JS |
+-------------+------------------+
2 rows in set (0.00 sec)
mysql> select * from answer;
+----------+----------------------------------------------+----------------------+
| answerid | answer | question_question_id |
+----------+----------------------------------------------+----------------------+
| 1 | Java is a programming language | 101 |
| 2 | Java is pure Object oriented language | 101 |
| 3 | Java is a High level language | 101 |
| 4 | React is a open source developed by Facebook | 201 |
| 5 | React is a JAvascript Library | 201 |
| 6 | React is used for SPA | 201 |
+----------+----------------------------------------------+----------------------+