Search code examples
sqlspringstringjpajpql

@Query: How to Build complete SQL manually? (Spring JPA)


I wan to build my sql statement manually with Java and then provide a final string to my repository like this:

public interface EventRepository extends CrudRepository<Event, Long>{

@Query("?1") 
List<Event> getLatestEventsFiltered(String sql); 
    
}

This doesn´t work because it is not according to syntax...it says : QuerySyntaxException: unexpected token: ?

But how to achive what I intent to do?

Thanks in advance!


Solution

  • You can't do that with @Query annotation.

    First, we have to create a custom interface that declares our custom method:

    public interface EventRepository extends CrudRepository<Event, Long> {
        List<Event> getLatestEventsFiltered(String sql);
    }
    
    public interface EventRepositoryCustom {
        List<Event> getLatestEventsFiltered(String sql);
    }
    

    Next, we'll provide our implementation of the EventRepository interface:

    @Repository
    public class EventRepositoryImpl implements EventRepositoryCustom {
    
        @PersistenceContext
        private EntityManager entityManager;
    
        @Override
        public List<Event> getLatestEventsFiltered(String sql) {
            Query query = entityManager.createNativeQuery(sql, Event.class);
            // You can use alternative query method instead of native query.
            List<Event> resultList = (List<Event>) query.getResultList();
            return resultList;
        }
    }
    

    Alternatively, another possibility that allows you to do pretty much anything is by using the Specification API. It allows you to create programmatically instead of a direct sql statement.