How to add a specific field in Spring Data Rest?

て烟熏妆下的殇ゞ 提交于 2019-12-02 20:04:11

问题


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

When I select in JPQL as above, 'avg (rl.rating) as rating' column does not have the name like the image below.

enter image description here

rating: 4.0
I would like to do this service.

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.


回答1:


You can use projection in the output of your repo method.

  1. So in your case you can set a projection, for example:
@Projection(name = "BookWithRating", types = { Book.class }) 
interface BookWithRating { 

  Float getRating(); 

  Book getBook(); 
}
  1. Then setup a query method:
@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);

Pay attention to the alias of the output parameters - their names must match the projection getters.

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').



来源:https://stackoverflow.com/questions/42927756/how-to-add-a-specific-field-in-spring-data-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!