Explanation of JPA annotations and property values


What is JPA?
  • In relational databases, we need to map entities to make relationships between them. 
  • Java Persistence API helps us to do this task. 
  • Actually, JPA is a specification for accessing, persisting, and managing data between Java objects, classes and relational databases.
  • JPA provides guidelines to develop an interface that complies with a certain standard. 
  • But JPA doesn't provide any implementation for that interface. Hibernate will do the implementation. 

Example entity

package com.app.entity;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Entity
@Data
@Table(name = "employee")
@SequenceGenerator(name = "employee_gen", sequenceName = "employee_seq", allocationSize = 100)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "emp_id", nullable = false, unique = true)
private Integer id;
@Column(name = "emp_first_name")
private String firstName;
@Column(name = "emp_last_name")
private String lastName;
@Column(name = "emp_email")
private String email;
@Column(name = "emp_mobile_number")
private String mobileNumber;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinColumn(name = "fk_department_id", updatable = false)
@JsonManagedReference
@EqualsAndHashCode.Exclude
private Department department;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinTable(name = "employee_roles",
joinColumns = {@JoinColumn(name = "employee_id")},
inverseJoinColumns = {@JoinColumn(name = "role_id")})
@JsonManagedReference
private List<Role> roles;
}
view rawEmployee.java hosted with ❤ by GitHub

Annotations and properties 

@Entity
  • This annotation specifies the class can be mapped to a database table. 
  • If you make an entity class, @Id annotation is mandatory. 
@Table(name = "employee")
  • This annotation can be used to specify the table name of the related class. 
  • If you don't mention the table name using @Table annotation, JPA will take the class name as the table name.
@Data
  • This is not a JPA annotation. 
  • It is from the Lombok library to add getters and setters of the fields of the class.
@Id
  • This specifies the member field is the primary key of the current entity.
@GeneratedValue(strategy = GenerationType.AUTO, generator = "employee_gen")
  • This specifies the way of increment of the member field. 
  • It refers to which sequence generator you want to use.
@SequenceGenerator(name = "employee_gen", sequenceName = "employee_seq", allocationSize = 100)
  • This establishes the relation between the database and the entity. 
  • First, you need to create and sequence on the database side.
sequenceName
  • You need to specify this if the sequenceName and the name are different. 
  • Name is the sequence name that is created on the database side.
@OneToMany(mappedBy = "department", fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
  • This specifies OneToMany mapping
mappedBy = "department"
  • Once we have defined the owning side of the relationship, Hibernate is smart enough to map that relationship in the database. 
  • To make this association bidirectional, we have to define the reference side as well.
  • MappedBy annotation will do it for us. 
  • The value of the mappedBy annotation is the name of the association mapping attribute on the owning side.
fetch
  • By default @ManyToOne and @OneToOne annotations are fetched EAGER and @OneToMany and @ManyToMany are fetched LAZY.
  • EAGER means to load data  on the spot
  • LAZY means to load data on demand
  • The best practice is to set child entities LAZY.
cascade
  • In cascade, after one operation (save, update and delete) is done, it decides whether it needs to call other operations (save, update and delete) on other entities that have relationships with each other. 
  • The cascade types supported by the Java Persistence Architecture are as below:

  1. CascadeType.PERSIST : means that save() or persist() operations cascade to related entities.
  2. CascadeType.MERGE : means that related entities are merged into the managed state when the owning entity is merged.
  3. CascadeType.REFRESH : does the same thing for the refresh() operation.
  4. CascadeType.REMOVE : removes all related entities associated with this setting when the owning entity is deleted.
  5. CascadeType.DETACH : detaches all related entities if a “manual detach” occurs.
  6. CascadeType.ALL : is shorthand for all of the above cascade operations.
@JsonManagedReference
  • Both @JsonManagedReference and @JsonBackReference annotations are used to handle circular references between two entities. 
  • This is the forward part of a reference and it will serialize normally.
  • Usually, this is used on the parent entity
@JsonBackReference
  • This will be omitted from serialization.
  • Usually, this annotation is used in the child entity.
@JsonIgnore
  • This simply ignores one side of the relationship and it is used to avoid the infinite recursion of two entities. 
@JsonIdentityInfo
  • This can be also used to deserialize with a bidirectional relationship
@JoinColumn(name = "fk_department_id", updatable = false)
  • In OneToMany or ManyToOne relationship, the owning side is usually defined as the "many" side of the relationship. 
  • It is usually the side that owns the foreign key.
name = "fk_department_id"
  • This means the Employee entity will have a foreign key column named "fk_department_id" referring to the primary key of the Department entity.


Explanation of JPA annotations and property values Explanation of JPA annotations and property values Reviewed by Ravi Yasas on 11:42 PM Rating: 5

No comments:

Powered by Blogger.