我有两个实体:“user”和“request”:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Builder.Default
@OneToMany(cascade = {CascadeType.ALL}, mappedBy = "user", orphanRemoval = true)
private List<Request> requests = new ArrayList<>();
@Entity
@Table(name = "request")
public class Request {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "start_date")
private LocalDate startDate;
@Column(name = "end_date")
private LocalDate endDate;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
我想得到一个结果集,它能够根据这两个实体的字段进行排序。按姓氏(来自用户)和开始日期(来自请求)。
以下是我的标准api类:
@Override
public Page<Request> getRequests(Integer userId, PageableRequest request) {
Pageable pageable = request.getPageRequest();
int pageSize = pageable.getPageSize();
long offset = pageable.getOffset();
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Request> criteriaQuery = cb.createQuery(Request.class);
Root<Request> requestRoot = criteriaQuery.from(Request.class);
Predicate userPredicate = criteriaBuilder.equal(root.get(Request_.USER).get(User_.ID), userId);
CriteriaQuery<Request> select = criteriaQuery.select(requestRoot)
.where(userPredicate)
.orderBy(QueryUtils.toOrders(pageable.getSort(), requestRoot, cb));
TypedQuery<Request> typedQuery = entityManager.createQuery(select);
typedQuery.setFirstResult((int) offset);
typedQuery.setMaxResults(pageSize);
Long count = getTotalCount(cb);
return new PageImpl<>(typedQuery.getResultList(), pageable, count);
}
我希望能够排序方式:sort=lastname或sort=startdate
以下是不起作用的选项:
.orderBy(QueryUtils.toOrders(pageable.getSort(), requestRoot.join(User_.LAST_NAME), cb));
和
.orderBy(QueryUtils.toOrders(pageable.getSort(), requestRoot.join(Request.USER), cb));
如何能够同时按根实体(请求)和加入的(用户)进行排序?
暂无答案!
目前还没有任何答案,快来回答吧!