Spring Data JPA Find by Enum Value

In Spring Data JPA, you can easily query entities by their attributes, including Enum types. Here's a step-by-step guide to illustrate how you can create a repository method to find entities by an Enum value.

Define the Enum

public enum Status {
    ACTIVE,
    INACTIVE,
    SUSPENDED
}

Use the Enum in your Entity

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    
    @Enumerated(EnumType.STRING) // Store the enum as a string in the database
    private Status status;

    // getters, setters, etc.
}

Create a Repository

public interface UserRepository extends JpaRepository<user long=""> {
    List<user> findByStatus(Status status);
}
In the repository, findByStatus is a derived query method. Spring Data JPA will generate the necessary query behind the scenes to fetch the users with the given status.

Using the Repository in Service Class

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    public List<user> findUsersByStatus(Status status) {
        return userRepository.findByStatus(status);
    }
}

In your service or controller, you can now call findUsersByStatus(Status.ACTIVE) to get all users with an ACTIVE status.

Note: The @Enumerated(EnumType.STRING) annotation is used to store the Enum values as strings in the database. If you don't use this annotation, JPA will, by default, store the Enum values as integers (ordinal values), which can cause issues if you later modify the order or values in the Enum. Storing them as strings makes your database values more readable and avoids potential issues related to ordinal storage.

Comments