Skip to main content

Hibernate (or JPA) - Using "mappedBy" attribute of mapping annotations(like @OneToOne, @OneToMany, @ManyToMany)

Using "mappedBy" attribute of mapping annotations(like @OneToOne, @OneToMany, @ManyToMany) for bi-directional relationship. This attribute allows you to refer the associated entities from both sides. If "X" has association with "Y" then you can get X from Y and Y from X.

For example, If you have "Book" entity and "Author" entity those are associated to each other in the way that Book has a Author and Author associated with a Book.
Now if you retrieve the Book Object from hibernate session, then you can get the Author entity from Book entity. Or if you get the Author entity then you can get the Book entity from Author entity.
So you require the bidirectional navigation relationships between Book and Author entities.

This is achieved in the Hibernate using the  @OneToOne relationship provided that child entity must have property type of parent and marked with annotation @OneToOne(mappedBy="parent") where parent is the Owner entity of this child entity.


package entity;

import javax.persistence.CascadeType;
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 = "Book")
public class Book {
    private int id;
    private String title;
    private String content;
    private Author author;

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
    
    @OneToOne(cascade=CascadeType.ALL)
    public Author getAuthor() {
        return author;
    }

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

    @Override
    public String toString() {
        return "Book [id=" + id + ", title=" + title + ", content=" + content
                + ", author=" + author.getId() + "]";
    }
    
}


package entity;

import javax.persistence.*;

@Entity
@Table(name = "Author")
public class Author {
    private int id;
    private String name;
    private String email;
    private long phone;
    private Book book;
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public long getPhone() {
        return phone;
    }

    public void setPhone(long phone) {
        this.phone = phone;
    }
    @OneToOne(mappedBy="author")
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Override
    public String toString() {
        return "Author [id=" + id + ", name=" + name + ", email=" + email
                + ", phone=" + phone + ", book=" + book.getId() + "]";
    }
    
}


Testing classes

Inserting records


import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import entity.Author;
import entity.Book;


public class Insert {
    public static void main(String[] args) {
        Configuration cfg=new Configuration();
        SessionFactory sf=cfg.configure("hibernate.cfg.xml").buildSessionFactory();
        Session session = sf.openSession();
        
        Author author=new Author();
        author.setEmail("author@gmail.com");
        author.setName("name");
        author.setPhone(543653465L);
        
        Book book1=new Book();
        book1.setAuthor(author);
        book1.setContent("re  td e sdf asdfasdfasd f");
        book1.setTitle("java");
        
        session.beginTransaction();
        session.save(book1);
        session.getTransaction().commit();
        
    }
}

Retrieving Records

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import entity.Author;
import entity.Book;

public class update {
    public static void main(String[] args) {
        Configuration cfg=new Configuration();
        SessionFactory sf=cfg.configure("hibernate.cfg.xml").buildSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
        
        //Book book = (Book) session.get(Book.class, 2);
        //System.out.println(book.getAuthor());
        
        Author author = (Author) session.get(Author.class3);
        System.out.println(author.getBook());
        //book.getAuthor().setName("Test Author");
        //session.getTransaction().commit();
        
    }
}

hibernate configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">hemraj</property>
        <property name="connection.password">hemraj</property>
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        <mapping class="entity.Library"/>
        <mapping class="entity.Book"/>
        <mapping class="entity.Author"/>
    </session-factory>
</hibernate-configuration>

Comments

Anonymous said…
Very useful example. Thank you so much. It saved my one day since I had been struggling to find parent entity of child entity.
Unknown said…
Good explanation of mappedBy attribute. Thank u
Unknown said…
Very good explanation! I'd even say it's great! Thanks.
Unknown said…
i don't see any diffrences in all retrival cases. i am able to data in all 3 cases.
please tell me about mappedby attribute.

Popular posts from this blog

Using HyperSQL (HSQLDB)

HSQLDB is a portable RDBMS implemented in pure java. It can be embedded with your application as well as can be used separately. It is very a small database that supports almost all features of the standard database system. It comes with small jar file that can be found in lib folder. The HSQLDB jar package is located in the /lib directory of the ZIP package and contains several components and programs. Core components of jar file are : HyperSQL RDBMS Engine (HSQLDB), HyperSQL JDBC Driver, Database Manager, and Sql Tool. Installing and Using Download: download latest release of HyperSQL database from http://hsqldb.org website and extract it. You will see following contents. Here "bin" directory contains some batch files those can be used to run a swing based GUI tool. You can use runManagerSwing.bat to connect to database, but database must be on before running it. Directory lib contains File hsqldb.jar . It is the database to be used by you. Running database First

How to handle values from dynamically generated elements in web page using struts2

Some time you will see the form containing the button " Add More " . This facility is provided for the user to get the values for unknown number of repeating for some information. for example when you are asking to get the projects details from user, you need to put the option to add the more project for the user since you don't known how many projects user have. In the HTML form, you repeat the particular section to get the multiple values for those elements. In Html page , you can put the option to add new row of elements or text fields by writing the java script or using JQuery API. Now, the question is that how to capture the values of dynamically generated text fields on the server. Using the servlet programming you can get the values by using getParameters() method that resultants the array of the parameter having the same name. But this limit you to naming the text fields in the HTML form. To ally this approach, you have to take the same name for t

In Process Mode of HSQLDB in web application.

If you want to use the database into your web application, you can use the HSQLDB in In_Process mode. In this mode, you can embed the HSQLDB into your web application and it runs as a part of your web application programm in the same JVM. In this mode, the database does not open any port to connect to the application on the hosing machine and you don't need to configure anything to access it. Database is not expposed to other application and can not be accessed from any dabase tools like dbVisualizer etc. In this mode ,database will be unknown from any other person except you. But in the 1.8.0 version, you can use Server intance for external as well as in process access.  To close the databse, you can issue SHUTDOWN command as an SQL query.   In the in-process mode, database starts from JDBC with the associated databse file provided through  connection URL. for example   DriverManager.getConnection("jdbc:hsqldb:mydatabase","SA","");   Here myd