Mark As Completed Discussion

Hibernate and JPA

In Spring Boot applications, Hibernate and JPA (Java Persistence API) are commonly used to interact with databases and perform object-relational mapping (ORM). Hibernate is an ORM framework that provides a convenient way to map Java objects to database tables, while JPA is a specification that defines a set of interfaces and annotations for working with ORM frameworks.

Object-Relational Mapping

Object-relational mapping is a technique used to map object-oriented concepts to relational database concepts. With ORM, you can model your database tables as Java classes and perform database operations using object-oriented syntax.

For example, let's consider an Employee class that represents an employee in a company:

TEXT/X-JAVA
1@Entity
2@Table(name = "employees")
3public class Employee {
4
5    @Id
6    @GeneratedValue(strategy = GenerationType.IDENTITY)
7    private int id;
8
9    @Column(name = "first_name")
10    private String firstName;
11
12    @Column(name = "last_name")
13    private String lastName;
14
15    @Column(name = "email")
16    private String email;
17
18    // Constructors, getters, setters
19
20}

In the above code, the @Entity annotation marks the class as an entity, which corresponds to a database table. The @Table annotation specifies the name of the database table associated with the entity. Each attribute of the class is annotated with @Column to map it to a column in the table.

CRUD Operations with Hibernate

Hibernate provides a set of APIs and methods for performing CRUD (Create, Read, Update, Delete) operations on entities. These operations can be performed using Hibernate's Session or EntityManager.

Here's an example of how you can use Hibernate to perform CRUD operations on the Employee entity:

TEXT/X-JAVA
1@Repository
2public class EmployeeRepository {
3
4    @PersistenceContext
5    private EntityManager entityManager;
6
7    public Employee save(Employee employee) {
8        entityManager.persist(employee);
9        return employee;
10    }
11
12    public Employee findById(int id) {
13        return entityManager.find(Employee.class, id);
14    }
15
16    public List<Employee> findAll() {
17        return entityManager.createQuery('SELECT e FROM Employee e', Employee.class).getResultList();
18    }
19
20    public Employee update(Employee employee) {
21        return entityManager.merge(employee);
22    }
23
24    public void delete(Employee employee) {
25        entityManager.remove(employee);
26    }
27
28    // Other methods
29
30}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment