Hibernate One to many (@OneToMany) relationship

onetomany

To create the relationship from one parent to multiple children, we use @OneToMany mapping in hibernate or JPA. Here is the example of how to use @OneToMany annotation.

package example.configuration.demo7;

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

@Entity
@Table(name="book")
public class Book {
	
	@Id
	@GeneratedValue
	private int id;
	private String title;
	private float price;
	
	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;
	}
}

 

 

package example.configuration.demo7;

import java.util.List;

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

 

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();
		
		
		Book book1=new Book();
		book1.setTitle("Learning Hibernate");
		book1.setPrice(2342);
		session.save(book1);
		
		Book book2=new Book();
		book2.setTitle("Java");
		book2.setPrice(333);
		session.save(book2);
		
		List<Book> books=new ArrayList<>();
		books.add(book1);
		books.add(book2);
		
		Author author=new Author();
		author.setName("John");
		author.setEmail("john@gmail.com");
		author.setBooks(books);
		
		session.save(author);
		
		tx.commit();
		session.close();
	}
}

 

@OneToMany tables

Tags