Getting Started with Spring Data JPA and Hibernate in Spring Boot

To get started with Spring Data JPA and Hibernate in a Spring Boot application, follow these steps:

1. Add Required Dependencies

Include spring-boot-starter-data-jpa and h2 (or any other database) dependencies in your pom.xml (for Maven projects).

Maven:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

2. Configure the Application Properties

Set up the database configurations in application.properties or application.yaml. Below is an example for H2 database:
application.properties:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

3. Create an Entity Class

Create a Java class annotated with @Entity to represent your database table. Also, use mapping annotations (@Id, @GeneratedValue, etc.) to configure the primary key and other relationships.

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String department;
    private Double salary;

    // Constructors, Getters, and Setters
    public Employee() {}

    public Employee(String name, String department, Double salary) {
        this.name = name;
        this.department = department;
        this.salary = salary;
    }

    // Getters and Setters
    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }
}

4. Create a Spring Data JPA Repository

Create an interface for the repository that extends JpaRepository

import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    // You can define custom query methods here if needed
}

5. Create a Spring Boot Service

Add a service layer to encapsulate business logic and interact with the repository.

import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {

    private final EmployeeRepository employeeRepository;

    public EmployeeService(EmployeeRepository employeeRepository) {
        this.employeeRepository = employeeRepository;
    }

    public List<Employee> getAllEmployees() {
        return employeeRepository.findAll();
    }

    public Employee saveEmployee(Employee employee) {
        return employeeRepository.save(employee);
    }
}

6. Create a Controller

Now, create a REST Controller to expose APIs for interacting with your service.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping
    public List<Employee> getAllEmployees() {
        return employeeService.getAllEmployees();
    }

    @PostMapping
    public Employee createEmployee(@RequestBody Employee employee) {
        return employeeService.saveEmployee(employee);
    }
}

7. Run the Application

Run your Spring Boot application (@SpringBootApplication annotated class) and test your REST endpoints.

  • GET /employees → Retrieve all employees
  • POST /employees → Add a new employee (pass JSON body)

Example JSON for the POST request:

{
    "name": "John Doe",
    "department": "Engineering",
    "salary": 65000.00
}

8. Testing

You can use tools like Postman, Curl, or Spring Boot DevTools to verify that your application works as expected.

9. Switching to a Production Database

Replace the H2 configurations with your production database configurations (e.g., MySQL, PostgreSQL).
For example, using MySQL:

Dependencies:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

This basic setup is a starting point.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.