Generate String UUID Primary Keys in Spring Boot

In modern application development, UUIDs (Universally Unique Identifiers) are widely used as primary keys in databases due to their unique characteristics and advantages. In this blog post, we'll explore how to generate String UUID primary keys in a Spring Boot application using the latest Spring Boot 3, Hibernate 6 and the H2 database. We'll use a Student entity as our example and discuss how UUID support as strings works in this context.

Prerequisites

Before we get started, ensure you have the following:

  • Java Development Kit (JDK) installed
  • A Spring Boot project set up (you can create one using Spring Initializr)
  • Basic knowledge of Spring Boot and JPA (Java Persistence API)

Step 1: Setting Up the Project

If you haven't already set up a Spring Boot project, create one using Spring Initializr with the following dependencies:

  • Spring Web
  • Spring Data JPA
  • H2 Database (for simplicity, but you can use any database of your choice)

Step 2: Configuring the Entity

We'll create a Student entity class with a String UUID primary key using the Jakarta package. In the latest versions of Spring Boot and Hibernate, you can use the GenerationType.UUID strategy directly in the @GeneratedValue annotation.

Here is an example of a Student entity:

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

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private String id;  // String type for storing UUIDs as strings
    private String name;
    private String email;

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

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

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

How UUID Support as Strings Works

UUID Generation: 

  • The @GeneratedValue(strategy = GenerationType.UUID) annotation tells Hibernate to generate a UUID for the id field. 
  • Hibernate automatically converts the generated UUID into a string before storing it in the database. 

Storage and Retrieval: 

  • When a new Student entity is persisted, Hibernate generates a UUID, converts it to a string, and stores it in the database. 
  • The string is converted back into a UUID format when the entity is retrieved from the database.

Step 3: Creating the Repository

Next, create a repository interface for the Student entity. Spring Data JPA provides a convenient way to interact with the database using repositories.

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

public interface StudentRepository extends JpaRepository<Student, String> {
}

Step 4: Creating the Service

We'll create a service class to handle the business logic for our Student entity. The service will interact with the repository to perform CRUD operations.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    public Optional<Student> getStudentById(String id) {
        return studentRepository.findById(id);
    }

    public Student createStudent(Student student) {
        return studentRepository.save(student);
    }

    public void deleteStudent(String id) {
        studentRepository.deleteById(id);
    }
}

Step 5: Creating the Controller

Finally, create a controller to expose RESTful endpoints for managing Student entities. This controller will use the StudentService to perform the necessary operations.

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

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public List<Student> getAllStudents() {
        return studentService.getAllStudents();
    }

    @GetMapping("/{id}")
    public Optional<Student> getStudentById(@PathVariable String id) {
        return studentService.getStudentById(id);
    }

    @PostMapping
    public Student createStudent(@RequestBody Student student) {
        return studentService.createStudent(student);
    }

    @DeleteMapping("/{id}")
    public void deleteStudent(@PathVariable String id) {
        studentService.deleteStudent(id);
    }
}

Testing the Application

Now that everything is set up, you can run your Spring Boot application. You can use tools like Postman or cURL to interact with the RESTful API endpoints. Here are some example requests:

  1. Create a new student:

    POST /students
    Content-Type: application/json
    
    {
        "name": "John Doe",
        "email": "john.doe@example.com"
    }
    
  2. Get all students:

    GET /students
    
  3. Get a student by ID:

    GET /students/{id}
    
  4. Delete a student by ID:

    DELETE /students/{id}
    

Conclusion

In this blog post, we demonstrated how to generate String UUID primary keys in a Spring Boot application using the latest Spring Boot 3, Hibernate and H2 in-memory database. Using String UUIDs provides a robust and scalable solution for primary keys, especially in distributed systems. By leveraging the GenerationType.UUID strategy, we can simplify our code and take advantage of Hibernate's built-in support for UUIDs.

Feel free to explore more features and customization options in Spring Data JPA and Hibernate to suit your application's needs. Happy coding!

Comments