Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use enum parameter into JpaRepository nativeQuery?

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?

like image 270
Tetiana Serediuk Avatar asked Jun 09 '17 14:06

Tetiana Serediuk


People also ask

What is use of nativeQuery true?

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.

What is nativeQuery JPA?

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.

What is @query in spring?

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.


1 Answers

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()}

like image 71
Ivar Avatar answered Oct 06 '22 08:10

Ivar