Thursday, 17 August 2017

Hibernate One-to-One mapping with Annotations with mappedBy

Hibernate One-to-One mapping with Annotations with mappedBy:

This Hibernate tutorial demonstrates how to use JPA annotations in order to implement a bidirectional one-to-one association on a foreign key.

mappedBy: The attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity. This also means that you can access the other table from the class which you've annotated with "mappedBy" (fully bidirectional relationship).

The annotation mappedBy ideally should always be used in the Parent side (Book class) of the bi directional relationship, in this case it should be in Book class pointing to the member variable 'book' of the Child class (Author class)


package com.hibernate.practice.onetoone;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

public class Book {

       private Long bookId;
       private String bookTitle;
       private String bookDescription;
       private Date publishedDate;
       private Author author;
       public Book(){

       public Long getBookId() {
             return bookId;

       public void setBookId(Long bookId) {
             this.bookId = bookId;
       public String getBookTitle() {
             return bookTitle;

       public void setBookTitle(String bookTitle) {
             this.bookTitle = bookTitle;
       public String getBookDescription() {
             return bookDescription;

       public void setBookDescription(String bookDescription) {
             this.bookDescription = bookDescription;
       public Date getPublishedDate() {
             return publishedDate;

       public void setPublishedDate(Date publishedDate) {
             this.publishedDate = publishedDate;
       @OneToOne(cascade = CascadeType.ALL)
       public Author getAuthor() {
             return author;

       public void setAuthor(Author author) {
    = author;

package com.hibernate.practice.onetoone;

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

public class Author {

       private Long authorId;
       private String name;
       private String email;
       private Book book;
       public Author(){
       public Author(String name, String email) { = name; = email;
       public Long getAuthorId() {
             return authorId;
       public void setAuthorId(Long authorId) {
             this.authorId = authorId;
       public String getName() {
             return name;
       public void setName(String name) {
    = name;
       public String getEmail() {
             return email;
       public void setEmail(String email) {
    = email;
       @OneToOne( mappedBy="author")
       public Book getBook() {
             return book;
       public void setBook(Book book) {
    = book;

package com.hibernate.practice.onetoone;

import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class BookManager {
       public static void main(String[] args) {
             // loads configuration and mappings
        Configuration configuration = new Configuration().configure();
        ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
        ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
        // builds a session factory from the service registry
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        // obtains the session
        Session session = sessionFactory.openSession();
     // creates a Book entity
        Book newBook = new Book();
        newBook.setBookTitle("Effective Java");
        newBook.setBookDescription("A Programming Language Guide (Java Series)");
        newBook.setPublishedDate(new Date());
        newBook.setAuthor(new Author("Joshua Bloch", ""));
        // persists the book entity
        Long bookId = (Long);
        // gets the book entity back
        Book book = (Book) session.get(Book.class, bookId);
        System.out.println("Book's Title: " + book.getBookTitle());
        System.out.println("Book's Description: " + book.getBookDescription());
        Author author = book.getAuthor();
        System.out.println("Author's Name: " + author.getName());
        System.out.println("Author's Email: " + author.getEmail());

Write XML configuration for database settings and mapping classes in the hibernate.cfg.xml file as follows:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@</property>
  <property name="hibernate.connection.username">PRACTICE</property>
  <property name="hibernate.connection.password">PRACTICE</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="show_sql">true</property>
       <!--Mapping Entity Starts -->
    <mapping class="com.hibernate.practice.onetoone.Book"/>
    <mapping class="com.hibernate.practice.onetoone.Author"/>
    <!--Mapping Entity Ends -->

Output of the program:

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Book's Title: Effective Java
Book's Description: A Programming Language Guide (Java Series)
Author's Name: Joshua Bloch
Author's Email:
Hibernate: insert into AUTHOR (EMAIL, NAME, AUTHOR_ID) values (?, ?, ?)
Hibernate: insert into BOOK (AUTHOR_ID, DESCRIPTION, TITLE, PUBLISHED, BOOK_ID) values (?, ?, ?, ?, ?)

You may also like to read the below posts:

Read More »