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)

Example:

Book.java

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;

@Entity
@Table(name="BOOK")
public class Book {

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

       @Id
       @Column(name="BOOK_ID")
       @GeneratedValue
       public Long getBookId() {
             return bookId;
       }

       public void setBookId(Long bookId) {
             this.bookId = bookId;
       }
      
       @Column(name="TITLE")
       public String getBookTitle() {
             return bookTitle;
       }

       public void setBookTitle(String bookTitle) {
             this.bookTitle = bookTitle;
       }
      
       @Column(name="DESCRIPTION")
       public String getBookDescription() {
             return bookDescription;
       }

       public void setBookDescription(String bookDescription) {
             this.bookDescription = bookDescription;
       }
       @Temporal(TemporalType.DATE)
       @Column(name="PUBLISHED")
       public Date getPublishedDate() {
             return publishedDate;
       }

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

       public void setAuthor(Author author) {
             this.author = author;
       }
}

Author.java

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;

@Entity
@Table(name="AUTHOR")
public class Author {

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

BookManager.java

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();
        registry.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
       
        // builds a session factory from the service registry
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
       
        // obtains the session
        Session session = sessionFactory.openSession();
        session.beginTransaction();
       
     // 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", "Joshua@gmail.com"));
       
        // persists the book entity
        Long bookId = (Long) session.save(newBook);
        
        // 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());
        
        session.getTransaction().commit();
        session.close();    
       }
}



Write XML configuration for database settings and mapping classes in the hibernate.cfg.xml file as follows:
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="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</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 -->
   
</session-factory>
</hibernate-configuration>

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: Joshua@gmail.com
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 »