Hibernate

One-to-One Relationship in Hibernate

Published on

One-to-one mapping in hibernate is a way to create a connection between two entities in a database so that one entity maps to exactly one instance of another entity. Both entities can connect unidirectionally or bidirectionally. We can treat it as a special relationship where each entity has a unique partner. You can create a one-to-one mapping in Hibernate using the @OneToOne annotation.

Lets understand one-to-one mapping by an example.

Imagine you have two tables in a database: Question and Answer. Each Question has only one Answer, and each Answer belongs to only one Question. This is called one-to-one relationship.

Lets write code for better understanding.

a) Create a maven project where artifactId(project name) is “OneToOneMapping” & groupId(package name) is “com.hiber.onetoone

b) Create a database table in mysql database name onetoonedb

Download Source Code here ⬇️(one-to-one-unidirectional)

Download source code here ⬇️ (one-to-one bidirectional)

1: 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.onetoone</groupId>
  <artifactId>OneToOneMapping</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>OneToOneMapping</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>

2: 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/onetoonedb</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.onetoone.Question"/>
		<mapping class="com.hiber.onetoone.Answer"/>
		
	</session-factory>
</hibernate-configuration>

3: Question.java

package com.hiber.onetoone;

import javax.persistence.*;

@Entity
public class Question {

	@Id
	private int qid;
	private String question;
	
	@OneToOne
	@JoinColumn(name = "answer_id")
	private Answer answer;

	public Question() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Question(int qid, String question, Answer answer) {
		super();
		this.qid = qid;
		this.question = question;
		this.answer = answer;
	}

	public int getQid() {
		return qid;
	}

	public void setQid(int qid) {
		this.qid = qid;
	}

	public String getQuestion() {
		return question;
	}

	public void setQuestion(String question) {
		this.question = question;
	}

	public Answer getAnswer() {
		return answer;
	}

	public void setAnswer(Answer answer) {
		this.answer = answer;
	}

	@Override
	public String toString() {
		return "Question [qid=" + qid + ", question=" + question + ", answer=" + answer + "]";
	}
	
	
}

4: Answer.java

package com.hiber.onetoone;

import javax.persistence.*;

@Entity
public class Answer {

	@Id
	private int ansId;
	private String answer;
	
	
	public Answer() {
		super();
		// TODO Auto-generated constructor stub
	}

	public int getAnsId() {
		return ansId;
	}
	public void setAnsId(int ansId) {
		this.ansId = ansId;
	}
	public String getAnswer() {
		return answer;
	}
	public void setAnswer(String answer) {
		this.answer = answer;
	}

		
}

5: App.java

package com.hiber.onetoone;

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

public class App {
	public static void main(String[] args) {

		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml");
		SessionFactory factory = cfg.buildSessionFactory();
		Question q1 = new Question();
		q1.setQid(101);
		q1.setQuestion("What is Java?");
		Answer answer1 = new Answer();
		answer1.setAnsId(234);
		answer1.setAnswer("Java is a programming language");
		q1.setAnswer(answer1);

		Question q2 = new Question();
		q2.setQid(102);
		q2.setQuestion("What is Hibernate?");
		Answer answer2 = new Answer();
		answer2.setAnsId(235);
		answer2.setAnswer("Hibernate is a ORM tool");
		
		q2.setAnswer(answer2);

		Question q3 = new Question();
		q3.setQid(103);
		q3.setQuestion("What s SQL?");
		Answer answer3 = new Answer();
		answer3.setAnsId(236);
		answer3.setAnswer("SQL is a programming Database language");
		
		q3.setAnswer(answer3);

		Session session = factory.openSession();
		Transaction transaction = session.beginTransaction();

		session.save(q1);
		session.save(q2);
		session.save(q3);
		session.save(answer1);
		session.save(answer2);
		session.save(answer3);
		transaction.commit();
		session.close();
	}
}

Output

mysql> use onetoonedb
Database changed
mysql> show tables;
+----------------------+
| Tables_in_onetoonedb |
+----------------------+
| answer               |
| question             |
+----------------------+
2 rows in set (0.00 sec)

mysql> select * from question;
+-----+--------------------+-----------+
| qid | question           | answer_id |
+-----+--------------------+-----------+
| 101 | What is Java?      |       234 |
| 102 | What is Hibernate? |       235 |
| 103 | What s SQL?        |       236 |
+-----+--------------------+-----------+
3 rows in set (0.00 sec)

mysql> select * from answer;
+-------+----------------------------------------+
| ansId | answer                                 |
+-------+----------------------------------------+
|   234 | Java is a programming language         |
|   235 | Hibernate is a ORM tool                |
|   236 | SQL is a programming Database language |
+-------+----------------------------------------+

Unidirectional Association

Download source code here ⬇️ (one-to-one unidirectional)

Above code example is unidirectional association because only one side of the relationship is aware of the other side. This means that we can navigate from one entity to another, but not the other way around. Here, Question entity is aware of Answer entity but Answer entity dont know about Qestion Entity.

Bidirectional Association

Download source code here ⬇️ (one-to-one bidirectional)

If both sides of the entity is aware of each other it means bidirectional association is defined & we can navigate from one entity(Question) to another(Answer) and back. In order to established such kind of associations we define references on both sides of the relationship.

Lets chnage the above code to establish two way relationshop between Answer & Question entity

1: Declare a Question type variable & create getter & setter.

2: In App.java , set question for every object of answer.

Question.java

package com.hiber.onetoone;

import javax.persistence.*;

@Entity
public class Question {

	@Id
	private int qid;
	private String question;
	
	@OneToOne
	@JoinColumn(name = "answer_id")
	private Answer answer;

	public Question() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Question(int qid, String question, Answer answer) {
		super();
		this.qid = qid;
		this.question = question;
		this.answer = answer;
	}

	public int getQid() {
		return qid;
	}

	public void setQid(int qid) {
		this.qid = qid;
	}

	public String getQuestion() {
		return question;
	}

	public void setQuestion(String question) {
		this.question = question;
	}

	public Answer getAnswer() {
		return answer;
	}

	public void setAnswer(Answer answer) {
		this.answer = answer;
	}

	@Override
	public String toString() {
		return "Question [qid=" + qid + ", question=" + question + ", answer=" + answer + "]";
	}
	
	
}

Answer.java

package com.hiber.onetoone;

import javax.persistence.*;

@Entity
public class Answer {

	@Id
	private int ansId;
	private String answer;
	
	@OneToOne
	private Question question;
	public Answer() {
		super();
		// TODO Auto-generated constructor stub
	}

	public int getAnsId() {
		return ansId;
	}
	public void setAnsId(int ansId) {
		this.ansId = ansId;
	}
	public String getAnswer() {
		return answer;
	}
	public void setAnswer(String answer) {
		this.answer = answer;
	}
	@Override
	public String toString() {
		return "Answer [ansId=" + ansId + ", answer=" + answer + "]";
	}
	public Answer(int ansId, String answer, Question question) {
		super();
		this.ansId = ansId;
		this.answer = answer;
		this.question = question;
	}

	public Question getQuestion() {
		return question;
	}

	public void setQuestion(Question question) {
		this.question = question;
	}
	
	
}

Output:

mysql> select * from question;
+-----+--------------------+-----------+
| qid | question           | answer_id |
+-----+--------------------+-----------+
| 101 | What is Java?      |       234 |
| 102 | What is Hibernate? |       235 |
| 103 | What s SQL?        |       236 |
+-----+--------------------+-----------+
3 rows in set (0.02 sec)

mysql> select * from answer;
+-------+----------------------------------------+--------------+
| ansId | answer                                 | question_qid |
+-------+----------------------------------------+--------------+
|   234 | Java is a programming language         |          101 |
|   235 | Hibernate is a ORM tool                |          102 |
|   236 | SQL is a programming Database language |          103 |
+-------+----------------------------------------+--------------+
3 rows in set (0.00 sec)

Click to comment

Popular Posts

Copyright © 2024 javadsa.com