'Spring Data JPA native-query works with @Query but not with @NamedNativeQuery
The following native-query works fine in the PersonRepository using @Query:
public interface PersonRepository extends JpaRepository<Person, Long> {
@Query(value="select * from person where name like %?", nativeQuery=true)
List<Person> findByPersonName(String name);
}
But the following (same native-query) does not work with @NamedNativeQuery:
@Entity
@NamedNativeQuery(name="Person.findByPersonName",
query="select * from person where name like %?")
public class Person {
@Id
@GeneratedValue
private Long id;
private String name;
}
public interface PersonRepository extends JpaRepository<Person, Long> {
List<Person> findByPersonName(String name);
}
It throws the following exception when personRepository.findByPersonName("Bates") is called:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [select * from person where name like %?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
Could someone help me understand why am I getting this error with @NamedNativeQuery, but not with @Query?
Solution 1:[1]
Adding the positional index 0 in the query of @NamedNativeQuery resolved the issue, as shown in the following code.
@Entity
@NamedNativeQuery(name="Person.findByPersonName",
query="select * from person where name like %?0")
public class Person {
@Id
@GeneratedValue
private Long id;
private String name;
}
public interface PersonRepository extends JpaRepository<Person, Long> {
List<Person> findByPersonName(String name);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | skip |
