Generate UUID as Primary Keys in Spring Boot

In modern software development, using UUIDs (Universally Unique Identifiers) as primary keys in databases has become increasingly popular. UUIDs offer several advantages over traditional auto-incrementing integer primary keys, such as uniqueness across distributed systems and improved security. In this blog post, we'll explore how to generate UUID primary keys in a Spring Boot application using the latest version of Spring Boot 3 and Hibernate framework 6.

Prerequisites

Before we dive into the implementation, ensure you have the following prerequisites:

  • Java Development Kit (JDK) installed - Java 17 or later
  • Spring Boot set up in your project (you can create a new project 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, you can create one using Spring Initializr. Choose 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

Let's create an entity class with a UUID primary key. 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 simple User entity:

import jakarta.persistence.*;
import java.util.UUID;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private UUID id;
    private String name;
    private String email;

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

    public void setId(UUID 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;
    }
}

Step 3: Creating the Repository

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

import org.springframework.data.jpa.repository.JpaRepository;
import java.util.UUID;

public interface UserRepository extends JpaRepository<User, UUID> {
}

Step 4: Creating the Service

Let's create a service class to handle the business logic for our User 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;
import java.util.UUID;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public Optional<User> getUserById(UUID id) {
        return userRepository.findById(id);
    }

    public User createUser(User user) {
        return userRepository.save(user);
    }

    public void deleteUser(UUID id) {
        userRepository.deleteById(id);
    }
}

Step 5: Creating the Controller

Finally, create a controller to expose RESTful endpoints for managing User entities. This controller will use the UserService 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;
import java.util.UUID;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    public Optional<User> getUserById(@PathVariable UUID id) {
        return userService.getUserById(id);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable UUID id) {
        userService.deleteUser(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 user:

    POST /users
    Content-Type: application/json
    
    {
        "name": "Ramesh Fadatare",
        "email": "[email protected]"
    }
    
  2. Get all users:

    GET /users
    
  3. Get a user by ID:

    GET /users/{id}
    
  4. Delete a user by ID:

    DELETE /users/{id}
    

Conclusion

In this blog post, we have demonstrated how to generate UUID primary keys in a Spring Boot application using the latest version of Spring Boot 3 and annotations. UUIDs provide a robust and scalable solution for primary keys, especially in distributed systems. By leveraging the GenerationType.UUID strategy, we can simplify our code and use 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