Hibernate one to one unidirectional with MySQL and Spring Boot

In this post, we will see Hibernate one to one unidirectional with MySQL and Spring Boot.

We are going to use a maven, embedded tomcat, postman and oracle database. Here we will have some rest endpoint which will be used to save and retrieve data in the database. After running the below example we will be able to save the Book and Story entity which is in one to one relationships.

Hibernate one to one unidirectional with MySQL and Spring Boot

Before going ahead, let’s see some points.

  • We have two entities Book.java and Story .java which are in one to one relation.
  • For this example, we are assuming one book can have only one story. The below example is a unidirectional relationship that means the Book entity can have a Story entity but the Story entity will not have a Book entity.
  • We are going to use two annotations @OneToOne and @JoinColumn for mapping.
  • We are not going to create a table, let’s hibernate do this job.
  • In case of @OneToOne default fetch type is EAGER.

Note –  Default Fetch type in case of the below annotations.

@OneToOne – Default fetch type is EAGER.
@OneToMany – Default fetch type is LAZY.
@ManyToOne – Default fetch type is EAGER.
@ManyToMany – Default fetch type is LAZY.

Hibernate one to one unidirectional with MySQL and Spring Boot from scratch.

We will use the spring boot library (will provide dependency in pom.xml) to make sure all necessary jar/library is easily available for our application. Spring boot will take care of all jars. Let’ s start.

Prerequisites –

  • JDK 1.8
  • Oracle 10g
  • Eclipse
  • maven
  • postman

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’click on next. Fill all details(GroupId – onetoonehibernatejpa, ArtifactId – onetoonehibernatejpa and name – onetoonehibernatejpa) and click on finish. Keep packaging as the jar.

Modify the pom.xml with the below code.

<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>onetoonehibernatejpa</groupId>
  <artifactId>onetoonehibernatejpa</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>onetoonehibernatejpa</name>
 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
 </parent>
 <dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
 
		</dependency>
 
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
 
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>
 
	</dependencies>
 
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
 
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>
 
 
		</plugins>
	</build>
</project>

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

Step 5 – Let maven download all necessary jar. Once it is done we will able to see the maven dependency folder which contains different jar files.

One to One Mapping Annotation Example in Hibernate/JPA using Spring Boot and Oracle

We are good now. We can start writing our controller classes, ServiceImpl and Repository. The directory structure of the application looks as below.

One to One Mapping Annotation Example in Hibernate/JPA using Spring Boot and Oracle

Step 6 – Define entity class i.e Book.java and Story.java.

Book.java

package com.onetoonehibernatejpa.entity;

import javax.persistence.*;
@Entity
public class Book {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int bookId;
 
	@Column(name = "book_name")
	private String bookName;
 
	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name = "storyiwd")
	private Story story;
 
	public Story getStory() {
		return story;
	}
 
	public void setStory(Story story) {
		this.story = story;
	}
 
	public int getBookId() {
		return bookId;
	}
 
	public void setBookId(int bookId) {
		this.bookId = bookId;
	}
 
	public String getBookName() {
		return bookName;
	}
 
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
 
}

Story.java

package com.onetoonehibernatejpa.entity;

import javax.persistence.*;


@Entity
public class Story {
 
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int storyId;
 
	@Column(name = "story_name")
	private String storyName;
	
	
	public int getStoryId() {
		return storyId;
	}
 
	public void setStoryId(int storyId) {
		this.storyId = storyId;
	}
 
	public String getStoryName() {
		return storyName;
	}
 
	public void setStoryName(String storyName) {
		this.storyName = storyName;
	}
	
 
}

Step 7 – Define the repository interface extending CrudRepository.

BookRepository.java

package com.onetoonehibernatejpa.repository;

import java.io.Serializable;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.onetoonehibernatejpa.entity.Book;
@Repository
public interface BookRepository extends CrudRepository<Book,Serializable> {
	public Book findByBookId(int bookId);
}

Step 8 – Define service interface i.e BookService.java

package com.onetoonehibernatejpa.service;

import org.springframework.stereotype.Component;

import com.onetoonehibernatejpa.entity.Book;

@Component
public interface BookService {
	public Book saveBook(Book book);
	public Book findByBookId(int bookId);
}

Step 9 – Define service implementation class.

BookServiceImpl.java

package com.onetoonehibernatejpa.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.onetoonehibernatejpa.entity.Book;
import com.onetoonehibernatejpa.repository.BookRepository;
import com.onetoonehibernatejpa.service.BookService;
 
@Service("bookServiceImpl")
public class BookServiceImpl implements BookService {
 
	@Autowired
	private BookRepository bookRepository;
 
	public Book saveBook(Book book) {
		book = bookRepository.save(book);
		return book;
 
	}
	
	public Book findByBookId(int bookId) {
		Book book = bookRepository.findByBookId(bookId);
		return book;
	}
}

Note – See here more about @Component, @Controller, @Service and @Repository annotations here.

Step 10 – Define the controller class or endpoint.

BookController.java

package com.onetoonehibernatejpa.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.onetoonehibernatejpa.entity.Book;
import com.onetoonehibernatejpa.service.BookService;
 
@RestController
@RequestMapping(value = "/book")
public class BookController {
	
	@Autowired
	private BookService bookService;
	
	
	@RequestMapping(value = "/savebook",method = RequestMethod.POST)
	@ResponseBody
    public Book saveBook(@RequestBody Book book) {
		Book bookResponse = bookService.saveBook(book);
		return bookResponse;
	}
	
	@RequestMapping(value = "/{bookId}",method = RequestMethod.GET)
        @ResponseBody
        public Book getBookDetails(@PathVariable int bookId) {
		Book bookResponse = bookService.findByBookId(bookId);
		
		return bookResponse;
	}
	
	
}

Note – See more details about @Controller and RestController here.

Step 11 – Define the JpaConfig.java

package com.onetoonehibernatejpa.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "com.onetoonehibernatejpa.repository")
public class JpaConfig {

}

Step 12 – Define the SpringMain.java

package com.onetoonehibernatejpa.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages="com.onetoonehibernatejpa.*")
@EntityScan("com.onetoonehibernatejpa.*")
public class SpringMain {
	public static void main(String[] args) {

        SpringApplication.run(SpringMain.class, args);
    }

}

Note – See more details about @ComponentScan here.

And finally, we have an application.properties file where we have database details.

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
 
 
spring.jpa.hibernate.ddl-auto =update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091

We are almost done. Run the application.

Let’s deploy the application running SpringMain class as a java application.

Now prepare the json data and try to save in the database.

Sample request JSON data-

{
"bookName":"rich dad poor dad",
 "story":{
   "storyName":"motivational story"
 }
}

Let’s test the save url.

One to One Mapping in Hibernate/JPA using Spring Boot and Oracle

Let’s check the database.

Hibernate one to one unidirectional with MySQL and Spring Boot

Yes, we have record in the book as well as story table. Did you notice storyiwd is the column in the book table is a foreign key? This is the primary key for the story table.

Let’s see in the below diagram which will give us a brief about flow.One to One Mapping in Hibernate/JPA using Spring Boot and Oracle

That’s all about Hibernate one to one unidirectional with MySQL and Spring Boot. If you feel any problem to run the application leave a comment.

You may like.

@OneToOne docs.

Summary – We have seen Hibernate one to one unidirectional with MySQL and Spring Boot. In one to one mapping one entity associated with another entity.