Ever wanted to rewrite a query in Spring Data JPA?
Sometimes, no matter how many features you try to apply, it seems impossible to get Spring Data JPA to apply every thing you’d like to a query before it is sent to the EntityManager
.
With 3.0.0-SNAPSHOT
(and targeted for the next milestone release train of Spring Data), you now have the ability to get your hands on the query, right before it’s sent to the EntityManager
and "rewrite" it. That is, you can make any alterations at the last moment.
Check it out below:
@Query
public interface MyRepository extends JpaRepository<User, Long> {
@Query(value = "select original_user_alias.* from SD_USER original_user_alias",
nativeQuery = true, queryRewriter = MyQueryRewriter.class) // (1)
List<User> findByNativeQuery(String param);
@Query(value = "select original_user_alias from User original_user_alias",
queryRewriter = MyQueryRewriter.class) // (2)
List<User> findByNonNativeQuery(String param);
}