How to add a specific field in Spring Data Rest?

2019-03-05 07:38发布

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条回答
神经病院院长
2楼-- · 2019-03-05 08:31

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

查看更多
登录 后发表回答