如何在Spring 数据中使用@query 注解指定return 哪些字段?
How to specify which fields to return with @query anotation in Spring Data?
当我 运行 在 Spring 引导中使用 @query 注释进行以下查询时,它 return 是正确的结果:
SELECT p FROM Collection p WHERE LOWER(p.description) LIKE LOWER(CONCAT('%',:searchTerm, '%'))
{
"_embedded": {
"collections": [
{
"place": "Blessington",
"description": "Collection of old shoes for recycling",
"_links": {
"self": {
"href": "http://localhost:8080/collections/1"
},
"collection": {
"href": "http://localhost:8080/collections/1"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/collections/search/findByDescription?searchTerm=shoe"
}
}
}
当我尝试将字段指定为 return 时:
SELECT p.description FROM Collection p WHERE LOWER(p.description) LIKE LOWER(CONCAT('%',:searchTerm, '%'))
我收到以下错误:
{
"cause": null,
"message": "PersistentEntity must not be null!"
}
如何在 Spring 数据中使用 @query 注释指定要 return 的字段?
是的,Manish post编辑 link 的问题似乎有答案。
答:不能。
Spring 数据将 return 整个实体,而不是单个字段。你不能让它那样做。如果你想这样做,你必须使用 projections。参见 linked post。
感谢@Manish
建议的 link 并未完全涵盖所有可能性。
从 Spring 数据的 Hopper 版本可以直接从查询方法直接 return 投影:
所以你可以这样做:
public interface ThingRepository extends JpaRepository<Thing, Long>{
@Query("select t from Thing t .....")
public List<ThingProjection> findBySomeCriteria(...);
}
当我 运行 在 Spring 引导中使用 @query 注释进行以下查询时,它 return 是正确的结果:
SELECT p FROM Collection p WHERE LOWER(p.description) LIKE LOWER(CONCAT('%',:searchTerm, '%'))
{
"_embedded": {
"collections": [
{
"place": "Blessington",
"description": "Collection of old shoes for recycling",
"_links": {
"self": {
"href": "http://localhost:8080/collections/1"
},
"collection": {
"href": "http://localhost:8080/collections/1"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/collections/search/findByDescription?searchTerm=shoe"
}
}
}
当我尝试将字段指定为 return 时:
SELECT p.description FROM Collection p WHERE LOWER(p.description) LIKE LOWER(CONCAT('%',:searchTerm, '%'))
我收到以下错误:
{
"cause": null,
"message": "PersistentEntity must not be null!"
}
如何在 Spring 数据中使用 @query 注释指定要 return 的字段?
是的,Manish post编辑 link 的问题似乎有答案。
答:不能。
Spring 数据将 return 整个实体,而不是单个字段。你不能让它那样做。如果你想这样做,你必须使用 projections。参见 linked post。
感谢@Manish
建议的 link 并未完全涵盖所有可能性。
从 Spring 数据的 Hopper 版本可以直接从查询方法直接 return 投影:
所以你可以这样做:
public interface ThingRepository extends JpaRepository<Thing, Long>{
@Query("select t from Thing t .....")
public List<ThingProjection> findBySomeCriteria(...);
}