如何在JPA存储库上编写此查询?

select TOP(10) id_libro, count(*) as occ from noleggi
group by id_libro
order by occ desc


我的实体:

public class Noleggio {

@Id
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;


@NotNull
@Column(name = "inizio_prestito")
private LocalDate inizioPrestito;

@NotNull
@Column(name = "fine_prestito")
private LocalDate finePrestito;

@NotNull
@ManyToOne
@JoinColumn(name = "id_utente")
private Utente utente;

@NotNull
@ManyToOne
@JoinColumn(name = "id_libro")
private Libro libro;

最佳答案

您可以使用@Query批注的nativeQuery属性将其应用于JPA存储库方法,该方法有时对于聚合或复杂查询非常有用,例如:

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

public interface NoleggioRepository extends CrudRepository<Noleggio, Long> {

    @Query(value = "select TOP(10) id_libro from noleggio order by occ desc", nativeQuery=true)
List<Noleggio> findSomethingFromNoleggio();

}


更多信息:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#NativeQueries

09-29 19:56