Hibernate - Use of mappedBy, Creating Bidirectional mapping

Hibernate have the many annotation to create the relationships between different entities like @OneToOne, @OneToMany, @ManyToOne etc. These annotation takes mappedBy parameter which is used to create the bidirectional mapping. In the bidirectional mapping, parent can retrieve the child and child can retrieve the parent.

Parent could point list of child entities and can have @OneToMany mapping annotation on the field which is connecting these two entities. this @OneToOne takes the paramter mappedBy which specify that which property of child entity will be used to refer this parent entity. In the following example books property is marked as @OneToMany relationship with book entities and mappedBy specifies that book entity will have the reference to this Author by author property.

package example.configuration.demo7;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Author{
 
	@Id
	@GeneratedValue
	private int id;
	private String name;
	private String email;
	
	@OneToMany(mappedBy="author", cascade = CascadeType.ALL)
	private List<Book> books;
	
	
	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 int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public List<Book> getBooks() {
		return books;
	}
	public void setBooks(List<Book> books) {
		this.books = books;
	}
	@Override
	public String toString() {
		return "Author [id=" + id + ", name=" + name + ", email=" + email + ", books=" + books + "]";
	}
	
}

Here is the child entity which has the reference to parent using the property "author" and this property marked as @ManyToOne which tells hibernate that many book entities will belongs to one author.

package example.configuration.demo7;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="book")
public class Book {
	 
	@Id
	@GeneratedValue
	private int id;
	private String title;
	private float price;
	
	@ManyToOne(cascade = CascadeType.ALL)
	private Author author;
	
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	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;
	}
	
	@Override
	public String toString() {
		return "Book [id=" + id + ", title=" + title + ", price=" + price + "]";
	}
	public Author getAuthor() {
		return author;
	}
	public void setAuthor(Author author) {
		this.author = author;
	}
	
	
}

Here is the code which persist the data in database. Here we have to save all entities after setting their relationships.

package example.configuration.demo7;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;


public class MainClass {
	public static void main(String[] args){
		
		StandardServiceRegistry registry=new StandardServiceRegistryBuilder().configure().build();
		SessionFactory factory=new MetadataSources(registry).buildMetadata().buildSessionFactory();
		Session session=factory.openSession();
		
		Transaction tx=session.beginTransaction();
		
		Author author=new Author();
		author.setName("John");
		author.setEmail("john@gmail.com");
		
		Book book1=new Book();
		book1.setTitle("Learning Hibernate");
		book1.setPrice(2342);
		book1.setAuthor(author);
		session.save(book1);
		
		Book book2=new Book();
		book2.setTitle("Java");
		book2.setPrice(333);
		book2.setAuthor(author);
		session.save(book2);
		
		List<Book> books=new ArrayList<>();
		books.add(book1);
		books.add(book2);
		
		
		author.setBooks(books);
		
		session.save(author);
		
	
		
		// Getting all books written by author having id 2
		Author author2 = session.get(Author.class, 2);
		System.out.println(author2);
		List<Book> list = author2.getBooks();
		for (Book book : list) {
			System.out.println(book);
		}
		
		// Getting author of the book having id 1
		Book book3=session.get(Book.class, 1);
		System.out.println("Author of book 1 is "+book3.getAuthor());
		
		tx.commit();
		session.close();
	}
}

Following the table structure that is generated because of this relationship.

entity relationships

Tags