Hibernate and Java Persistence API (JPA)
Hibernate is an open-source object-relational mapping (ORM) framework for Java. It provides a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate eliminates the need for manual SQL statements and provides a convenient way to perform CRUD (Create, Read, Update, Delete) operations.
Java Persistence API (JPA) is a specification for accessing, persisting, and managing data between Java objects and a relational database. It provides a high-level object-relational mapping (ORM) standard that is widely used in Java applications.
Entity Mapping
To use Hibernate and JPA, we need to map our Java classes to database tables. This is done using annotations.
Here's an example of an entity class mapping to a table named users
:
1import javax.persistence.*;
2
3@Entity
4@Table(name = "users")
5public class User {
6
7 @Id
8 @GeneratedValue(strategy = GenerationType.IDENTITY)
9 private Long id;
10
11 private String name;
12
13 private String email;
14
15 public User() {}
16
17 // getters and setters
18
19 public Long getId() {
20 return id;
21 }
22
23 public void setId(Long id) {
24 this.id = id;
25 }
26
27 public String getName() {
28 return name;
29 }
30
31 public void setName(String name) {
32 this.name = name;
33 }
34
35 public String getEmail() {
36 return email;
37 }
38
39 public void setEmail(String email) {
40 this.email = email;
41 }
42
43}
xxxxxxxxxx
}
import javax.persistence.*;
name = "users") (
public class User {
strategy = GenerationType.IDENTITY) (
private Long id;
private String name;
private String email;
public User() {}
// getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}