Do I have to avoid a native sql at spring data?

I have this repository:

public interface MessageRepository extends JpaRepository<Message, Long> {
    Message findById(long id);

    @Query(value = "SELECT * from message where sent = false and expire <= current_timestamp ", nativeQuery = true)
    List<Message> findAllReadyMessages();
}

Would it be a good idea to avoid using native SQL and push new date every time ? For example:

List<Message> findAllBySentForProcessingFalseAndExpireIsLessThanEqual(Date expire);

What are benifits and drawbacks ?

The first option is both more readable and secure in that you can’t pass a wrong date by accident.

The second option doesn’t explain anything about what you’re trying to achieve, and allows you to specify the parameter yourself. It’s not the same query as the first one in a logical sense.

IMHO you don’t have to avoid anything that gives you a good, clean solution, unless you work in a bureaucratic environment that gives you a set of silly rules you need to obey.

If you don’t want to pass Date object every time you call your repository method you can simply use a predefined JPA method CURRENT_TIMESTAMP.

Try this

public interface MessageRepository extends JpaRepository<Message, Long> {

    @Query(value = "SELECT m from Message m where m.sent = false and m.expire <= CURRENT_TIMESTAMP ")
    List<Message> findAllReadyMessages();

}