Embeddable types in hibernate

In database, sometime we have to treat the multiple fields as single a field. For example, address is the single field but again, it has multiple attributes. You can find many properties having the multiple attributes where you have to save the data for all attributes but you will treat that field as a one field.

Hibernate handles this scenarios using the embeddable type. This allows you to create the another type for the set of fields  and this new entity will become a field for your entity. In database, you will see all fields mapped in single table but in java, you will see the multiple classes of the beans.

package example.configuration.demo3.datamodel;

import javax.persistence.Embeddable;

@Embeddable
public class Author{

	private String name;
	private String email;
	
	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;
	}
}
package example.configuration.demo3.datamodel;

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

@Entity
@Table(name="book")
public class Book {
	@Id
	private int id;
	private String title;
	private float price;
	private Author author;
	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 float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public Author getAuthor() {
		return author;
	}
	public void setAuthor(Author author) {
		this.author = author;
	}
}
package example.configuration.demo3;

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;

import example.configuration.demo3.datamodel.Author;
import example.configuration.demo3.datamodel.Book;


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("johan@gmail.com");
		
		Book book=new Book();
		book.setId(1);
		book.setPrice(132);
		book.setTitle("Java");
		book.setAuthor(author);
		
		session.save(book);
		tx.commit();
		session.close();
	}
}

 

Tags