Monday 14 August 2017

Hibernate One-to-One mapping with Annotations with JoinColumn

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


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

@JoinColumn : The annotation @JoinColumn indicates that this entity is the owner of the relationship (that is: the corresponding table has a column with a foreign key to the referenced table)

We are going to develop a sample Hibernate application using the following technologies/software programs:
1.    Hibernate 4.2.6.Final
2.    JDK 7
3.    Eclipse IDE
4.    Oracle database

Note that we use the latest stuffs to date, you can use little bit lower or higher versions. Now, let’s following the steps below:
    Table of content:
1.    Creating Database and Tables
2.    Creating Eclipse Project
3.    Coding Model Classes with Annotations
4.    Writing Hibernate Configuration File
5.    Writing a Test Program

1. Creating Database and Tables

Execute the following SQL script to create  two tables author and book:

CREATE TABLE AUTHOR (
  AUTHOR_ID NUMBER(11) NOT NULL,
  NAME VARCHAR2(45),
  EMAIL VARCHAR2(45),
  PRIMARY KEY (AUTHOR_ID)
);

CREATE TABLE BOOK (
  BOOK_ID NUMBER(11) NOT NULL,
  TITLE VARCHAR(128),
  DESCRIPTION VARCHAR(512),
  PUBLISHED DATE,
  AUTHOR_ID NUMBER(11),
  PRIMARY KEY (BOOK_ID),
  CONSTRAINT AUTHOR_FK FOREIGN KEY (AUTHOR_ID) REFERENCES AUTHOR (AUTHOR_ID)
);
          COMMIT;

2. Creating Eclipse Project:

The project consists of the following files:

Model classes: Author.java and Book.java
Hibernate XML configuration file: hibernate.cfg.xml
Test program: BooksManager.java

Create a project in Eclipse with the following structure:
             
                                            



3. Coding Model Classes with Annotations:


The followings are code of the two model classes: Author.java and Book.java.

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.Table;

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

       private Long authorId;
       private String name;
       private String email;
      
       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;
       }

}

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;
       }
}


 As you notice, we use the following JPA annotations:
·       @Entity: is required for every model class.
·       @Table: maps the class with the corresponding database table. If omitted, Hibernate will use the class name.
·       @Column: maps the field with the corresponding table column. If omitted, Hibernate will infer the column name and type based on signatures of the getter/setter.
·       @Id and @GeneratedValue: are used in conjunction for a field that maps to the primary key. The values for this field are auto generated.
·       @Temporal: must be used with a java.util.Date field to specify the actual SQL type of the column.
·       @OneToOne and @JoinColumn: are used together to specify a one-to-one association and the join column.

4. Writing Hibernate Configuration File

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>

5. Writing a Test Program

Write code for the test program (BooksManager.java) as follows:

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();    
       }
}


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 (?, ?, ?, ?, ?)


Result in the Book and Author table:


                    




You may also interested in:


No comments:

Post a Comment