建议,我有下一个物体的结构:
class MovieWrapper {
private Movie movie;
}
class Movie {
private User user;
@Enumerated(EnumType.STRING)
private Status status;
}我只想通过用户Id和状态处于活动或挂起的位置从存储库查询MovieWrapper的第一次出现:
@Repository
public interface MovieWrapperRepository extends JpaRepository<MovieWrapper, Long> {
MovieWrapper findFirstByMovieUserIdAndMovieStatusActiveOrMovieStatusPending(Long userId);
}如何正确地做这件事?
发布于 2018-08-11 11:45:52
要从回购方法中获得“自定义”对象,您应该使用预测 (接口基投影更好,IMO)。
要实现复杂方法,您可以自己构建其查询,例如:
public interface MovieRepo extends JpaRepository<Movie, Long> {
Query("select m as movie from Movie m where m.user.id = ?1 and (m.status = 'ACTIVE' or m.status = 'PENDING')")
List<MovieProjection> findActiveOrPending(Long userId, Status status);
}其中MovieProjection是一个简单的接口:
public interface MovieProjection {
Movie getMovie();
}注意,对于查询中的别名m as movie,建议与投影一起使用,以避免某些错误。
更新
如果你只需要一个记录,你可以用一个技巧Pageable
public interface MovieRepo extends JpaRepository<Movie, Long> {
Query("select m as movie from Movie m where m.user.id = ?1 and (m.status = 'ACTIVE' or m.status = 'PENDING')")
List<MovieProjection> findAllActiveOrPending(Long userId, Status status, Pageable pageable);
default Optional<MovieProjection> getFirstOne(Long userId, Status status) {
return findAllActiveOrPending(userId, status, PageRequest.of(0, 1)).stream().findAny();
}
}这里我们取第一页有一个记录(PageRequest.of(0, 1) -参见这里)
https://stackoverflow.com/questions/51799079
复制相似问题