Entity looks like this:
@Getter @Setter @Entity public class Application { @Id private Long id; @Enumerated(EnumType.STRING) private ApplicationStatus status; }
Code works this way:
public interface ApplicationRepository extends JpaRepository<Application, Long> { @Query("SELECT app FROM #{#entityName} AS app WHERE app.status LIKE :status") List<Application> find(@Param("status") ApplicationStatus status);
But the same snippet with nativeQuery - doesn't:
@Query(value = "SELECT app.* FROM application AS app WHERE app.status LIKE :status", nativeQuery = true) List<Application> findNative(@Param("status") ApplicationStatus status); }
And I don`t have any exception, just empty list.
How can I fix this? Is it possible to use enum
with nativeQuery
?
P.S I can pass String
into method instead of ApplicationStatus
but maybe there are another option?
We can use @Query annotation to specify a query within a repository. Following is an example. In this example, we are using native query, and set an attribute nativeQuery=true in Query annotation to mark the query as native. We've added custom methods in Repository in JPA Custom Query chapter.
Native query refers to actual sql queries (referring to actual database objects). These queries are the sql statements which can be directly executed in database using a database client.
In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm. xml file.
Following similar question with similar requirement and one of the answers pointing to Spring Expression Language (SpEL) you could use:
public interface ApplicationRepository extends JpaRepository<Application, Long> { @Query(nativeQuery = true, value = "SELECT app FROM #{#entityName} AS app WHERE app.status=:#{#status.name()}") List<Application> find(@Param("status") ApplicationStatus status); }
Above important part is app.status=:#{#status.name()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With