Hibernate Entity Mappings

Now as you you have seen in the previous article how to create an Entity, now let’s see how to create relationships between Entities also called as Entity mappings, JPA defines four annotations for defining entities:

1. @OneToOne
2. @OneToMany
3. @ManyToOne
4. @ManyToMany

1. One-to-one relationships

The @OneToOne annotation is used to define a one-to-one relationship between two entities.

For example, you have a table EMPLOYEE and you want to store employee’s personal information(such as age, gender and grade) in another table, in that case you create another Entity and map both the entities by @OneToOne mapping, one instance of an Employee Entity class mapped to one instance of EmployeeProfile Entity.

import javax.persistence.*;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @Id @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "address")
    private String address;
	
    @OneToOne(mappedBy="emp")
    private EmployeeProfile profile;
	...
	
}
@Entity
public class EmployeeProfile {
   @Id
   private Integer id;
   private int age;
   private String gender;
   private String grade;
   @OneToOne
   private Employee emp;
   ...
}

The JPA provider uses EmployeeProfile’s emp field to map EmployeeProfile to Employee. The mapping is specified in the mappedBy attribute in the @OneToOne annotation.

2. One-to-many and many-to-one relationships

The @OneToMany and @ManyToOne annotations facilitate both sides of the same relationship.

Here’s an example where one Employee can have multiple Projects and a Project may have many other employees as well.
The Employee entity would define a @ManyToMany relationship with Project and the Project Entity would define a @OneToMany relationship with an Employee.

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @Id @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

	@ManyToOne
    @JoinColumn(name="PROJECT_ID")
    private Project project;
	...
}
@Entity
public class Project {
   @Id
   private Integer projectId;
   private String projectDescription;
   private String projectDuration;
   @OneToMany(mappedBy = "project")
   private List<Employee> emp = new ArrayList<>();
   ...
}

3. many-to-many relationships

Here’s a case where an Employee entity has many projects.

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @Id @GeneratedValue
    @Column(name = "EMP_ID")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

	@ManyToMany
    @JoinTable(name="EMP_PROJECTS",
    		   joinColumns=@JoinColumn(name="EMP_ID"),
    		   inverseJoinColumns=@JoinColumn(name="PROJECT_ID"))
    private Set<Project> projects = new HashSet<>();
	...
}
@Entity
public class Project {
   @Id
   private Integer projectId;
   private String projectDescription;
   private String projectDuration;
  
   @ManyToMany(mappedBy = "projects")
   private Set<Employee> projects = new HashSet<>();
   ...
}

In this example, we create a new table, EMP_PROJECTS, with two columns: EMP_ID and PROJECT_ID. Using the joinColumns and inverseJoinColumns attributes tells your JPA framework how to map these classes in a many-to-many relationship. The @ManyToMany annotation in the Employee class references the field in the Project class that manages the relationship; namely the projects property.

Summary

In this article we looked into the relational mapping between tables or entities in a JPA ORM way.
Hope you liked it !


Hibernate Cascading Levels

In Simple terms, Cascading in Hibernate means the propagation of same action(for eg: save, delete, etc.) from Parent to Child level entity.

Depending on what type of action to perform there are different cascade types.

Let’s have a look at an example:

Employee.java Entity Class

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @Id @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name="EMPLOYEE_ID")
    private Set<Project> projects;
	...
}

Project.java Entity Class

@Entity
public class Project {
   @Id
   private Integer projectId;
   private String projectDescription;
   private String projectDuration;
  
   @OneToOne (mappedBy="projects",  fetch = FetchType.LAZY)
   private Employee employee;
   ...
}

cascade=CascadeType.ALL” essentially means that any change which happens on Employee Entity must cascade to Project Entity as well. If you save an employee, then all associated projects will also be saved into database. If you delete an Employee then all projects associated with that Employee will also be deleted.

But what if we only want to cascade only save operations but not delete operation. Then we need to clearly specify it using correct CascadeType, see the below code.

@OneToMany(cascade=CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name="EMPLOYEE_ID")
private Set<Project> projects;

Now only when save() or persist() methods are called using employee instance then only projects will be persisted. If any other method is called on session, it’s effect will not affect/cascade to projects.

JPA – Cascade Types

The cascade types supported by the Java Persistence Architecture are as below:

  1. CascadeType.PERSIST : cascade type presist means that save() or persist() operations cascade to related entities.
  2. CascadeType.MERGE : cascade type merge means that related entities are merged when the owning entity is merged.
  3. CascadeType.REFRESH : cascade type refresh does the same thing for the refresh() operation.
  4. CascadeType.REMOVE : cascade type remove removes all related entities association with this setting when the owning entity is deleted.
  5. CascadeType.DETACH : cascade type detach detaches all related entities if a “manual detach” occurs.
  6. CascadeType.ALL : cascade type all is shorthand for all of the above cascade operations.

There is no default cascade type in JPA. By default no operations are cascaded.

Hibernate – Cascade Types

Now lets understand what is cascade in hibernate in which scenario we use it.

Apart from JPA provided cascade types, there is one more cascading operation in hibernate which is not part of the normal set above discussed, called “orphan removal“. This removes an owned object from the database when it’s removed from its owning relationship.

Let’s understand with an example. In our Employee and Project entity example, I have updated them as below and have mentioned “orphanRemoval = true” on projects. It essentially means that whenever I will remove a ‘ project from projects set’ (which means I am removing the relationship between that project and Employee); the project entity which is not associated with any other Employee on database (i.e. orphan) should also be deleted.

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @Id @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @OneToMany(orphanRemoval = true, mappedBy = "employee")
    private Set<Project> projects;
	...
}

Summary

In this tutorial, we have seen different ways to use cascade type operations in JPA hibernate.
I hope you liked it !


Hibernate Entity

What is an Entity in Hibernate? An Entity is a representation of a database table in Java POJO class(Plain old java object).

The Java Persistence API (JPA) is a Java specification that bridges the gap between relational databases and object-oriented programming.

ORM: Object-relational mapping

ORM tools like Hibernate, EclipseLink, and iBatis translate relational database models, including entities and their relationships, into object-oriented models.

Defining Entities

In order to define an entity, you must create a class that is annotated with the following :
1. @Entity : The @Entity annotation is a marker annotation, which is used to discover persistent entities.
2. @Table : If you wanted to map this entity to another table.

Now mapping Fields to Columns

1. @Column : You can override the default mapping by using the @Column annotation.
2. @Id  : to designate a field to be the table’s primary key. The primary key is required to be a Java primitive type, a primitive wrapper, such as Integer or Long, a String, a Date, a BigInteger, or a BigDecimal.

Example :

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   address    VARCHAR(150) default NULL,
   PRIMARY KEY (id)
);

Entity equivalent of the above Database Table

import javax.persistence.*;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @Id @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "address")
    private String address;

    public Employee() {}

    public int getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName( String first_name ) {
        this.firstName = first_name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName( String last_name ) {
        this.lastName = last_name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Summary

In this section, we learnt how to create a JPA Entity equivalent of a Database Table. Learnt about ORM object relational mapping.
Hope you liked it !