如何在 Spring Data Rest 中添加特定字段? [英] How to add a specific field in Spring Data Rest?
问题描述
我正在使用 Spring Data Rest 开发 Web 服务.
I am developing a web service using Spring Data Rest.
public interface BookRepository extends PagingAndSortingRepository<Book, Long> {
@Override
@Query("select avg(rl.rating) as rating, b from ReadingList rl join rl.book b group by rl.book order by rating desc")
Page<Book> findAll(Pageable pageable);
}
当我在 JPQL 中选择如上时,'avg (rl.rating) as rating' 列没有如下图所示的名称.
When I select in JPQL as above, 'avg (rl.rating) as rating' column does not have the name like the image below.
评分:4.0
我想做这项服务.
rating: 4.0
I would like to do this service.
另外,完整源码在github.https://github.com/ohgamja3/readinglist-rest-server/
In addition, the full source is in github. https://github.com/ohgamja3/readinglist-rest-server/
我需要有关此问题的帮助.感谢阅读.
I would like help with this issue. Thanks for reading.
推荐答案
您可以使用 projection 在您的 repo 方法的输出中.
You can use projection in the output of your repo method.
- 因此,在您的情况下,您可以设置投影,例如:
@Projection(name = "BookWithRating", types = { Book.class })
interface BookWithRating {
Float getRating();
Book getBook();
}
- 然后设置查询方法:
@Query("select avg(rl.rating) as rating, b as book from ReadingList rl join rl.book b group by rl.book order by rating desc")
Page<BookWithRating> findAllWithRating(Pageable pageable);
注意输出参数的别名 - 它们的名称必须与投影 getter 匹配.
Pay attention to the alias of the output parameters - their names must match the projection getters.
您也可以尝试使用 this 用于丰富数据模型的技术(请参阅如何使用 SpEL 表达式使用 @Value 注释公开的属性以公开合成属性").
Also you can try to use this technics for enriching a data model (see how to 'annotate exposed properties with @Value using SpEL expressions to expose synthetic properties').
这篇关于如何在 Spring Data Rest 中添加特定字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!