'Spring Data: can I create a method in the @Repository with a name what return list of object if String equals to constant?

Guess easier if I show you my example:

@Entity
class User {
    Long id;
    Status status;
}

enum Status {
   NEW("N"), DELETED("D")
}

I have an AttributeConverter on Status so in DB the enum is stored with one character.

In my database I have entities like:

Table user
------------
Id    Status
1       N
2       N
3       D
4       N
5       D

I want a method that list the Users with Status D. Something like this:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByStatusEqualsD();
    or
    List<User> findByStatusEqualsDeleted();
    problem is these are not working
}

I could write this:

List<User> findByStatus(Status status);

And call it as repo.findByStatus(Status.DELETED) but I want a method what returns only the deleted users.

If I call it as repo.findByStatus(Status.NEW) then it will return the new users.

I prefer to not write a @Query, I hope it is possible what I'm asking without doing it...

Thanks in advance.



Solution 1:[1]

Such behavior is not supported.

Method name is translated into JPQL expression (which is the same as used in @Query) with parameters in it (if needed) so you have to provide these. (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation)

If you want query parameters to be hardcoded - @Query is what you need.

Alternatively you can have default method in your repository calling the parametrized one as mentioned here JpaRepository with Enum: findAllByOfferState_ACTIVE. NoSuchElementException

Solution 2:[2]

Easy,

You don't need a repo for that. Create a Service instead:

public interface UserDAOService{
    List<User> getAllDeletedUsers();
}

And then just implement it with hardcoded findByStatus method from repo:

@Service
public class UserDAOServiceImpl implements UserDAOService{

    private final UserRepository userRepository;

    public UserDAOServiceImpl(UserRepository userRepository) {
        this.userRepository= userRepository;
    }

    
    @Override
    public List<Author> getAllDeletedUsers();
        return userRepository.findByStatus(Status.DELETED);
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 joykid
Solution 2