我想弄清楚如何在Spring Data Jpa中使用@NamedQuery
。據我所知,在普通的JPA中,@NamedQuery
可以用於代碼組織:查詢被定義一次,可以在任何地方用作常量。如何在Spring數據JPA的多個查詢方法中重用命名查詢?
我創建了一個示例來演示問題。我使用的查詢非常簡單,通常可以通過存儲庫方法名稱來表示。但它只是例如。
@Entity
@NamedQueries({
@NamedQuery(name = EXAMPLE_NAMED_QUERY,
query = "SELECT person FROM Person person WHERE person.id = :personId")
})
public class Person {
public static final String EXAMPLE_NAMED_QUERY = "Person.exampleNamedQuery";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String propertyOne;
private String propertyTwo;
protected Person() {}
public Person(String name, String propertyOne, String propertyTwo) {
this.name = name;
this.propertyOne = propertyOne;
this.propertyTwo = propertyTwo;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPropertyOne() {
return propertyOne;
}
public void setPropertyOne(String propertyOne) {
this.propertyOne = propertyOne;
}
public String getPropertyTwo() {
return propertyTwo;
}
public void setPropertyTwo(String propertyTwo) {
this.propertyTwo = propertyTwo;
}
}
現在,我想在我的SpringDataJPA-庫使用@NamedQuery
:
public interface PersonRepository extends JpaRepository<Person, Long> {
List<PersonProjectionOne> exampleNamedQueryProjectedByOne(@Param("personId") Long personId);
List<PersonProjectionTwo> exampleNamedQueryProjectedByTwo(@Param("personId") Long personId);
}
不過,我得到這個錯誤:
PropertyReferenceException: No property exampleNamedQueryWithOne found for type Person!
的文件說,庫法使用@NamedQuery
必須具有與命名查詢定義中的EntityName.XXX部分完全相同的名稱。我想對兩個方法使用相同的@NamedQuery
兩次,它們返回相同的數據但投影方式不同。根據這個答案:https://stackoverflow.com/a/25057982/5728559
However, if you want to re-use the query definition on multiple query methods, using a named query is still a reasonable option.
我認爲這在某種程度上是可能的。怎麼樣?