Show List
JPA
A JPA (Java Persistence API) is used to access, manage, and save data between Java object and relational database. JPA acts as a bridge between object-oriented Java classes and relational database systems. JPA is an approach for Object Relational Mapping (ORM). JPA only provides specifications. JPA implementation can be done through frameworks like Hibernate, TopLink, and iBatis etc.
JPA Advantages
- Simplifies Database Programming
- Provides database independent abstraction
- Helps avoid unnecessary queries
- Provides caching for faster application performance
JPA Annotations
JPA Interface provides below annotations. Hibernate, Spring JPA (and other JPA frameworks) provides the implementation of these annotations
- Define an Entity Class
- @Entity - Specifies that the class is an entity and is mapped to a database table
- @Table - Specifies the name of the database table to be used for mapping
@Entity
@Table(name = "emp_table")
public class Employee {
}
- Column Mapping
- @Column - It is an optional annotation that enables to customize the mapping between the entity attribute and the database column
- @Id - It corresponds to the primary key in the database table
- @GeneratedValue - Provides the specification of generation strategies for the values of primary keys
- @Enumerated - To map Java Enum type to a database column. Qualifier EnumType.STRING stores the value as string in database column. EnumType.ORDINAL stores the value as number.
- @Temporal - Used to map the date time Java object to a database column
- @Lob - To map a large object to a database column
public enum Rating {
Excellent,
Average,
Poor
}
@Entity
public class Movie {
@Id
@GeneratedValue
private int id;
@Enumerated(EnumType.STRING)
private Rating rating;
@Temporal(TemporalType.DATE)
private java.util.Date creationDate;
@Lob
@Column(name = "CHARS", columnDefinition = "CLOB")
private String chars;
}
- Association Mapping
- @ManyToMany
- @ManyToOne
- @OneToMany
- @OneToOne
Above annotations are used to define relationship between entities
public class Employee {
// ...
@ManyToOne
@JoinColumn(name = "employee_id", insertable = false, updatable = false)
private Department department;
//..
}
public class Department {
//..
@OneToMany
@JoinColumn(name = "employee_id")
private Set<Employee> employees;
//..
}
Leave a Comment