我遇到了这个复杂的SQL问题。
SELECT *
FROM t_shop s
LEFT JOIN (SELECT w.`shop_id`,
Min(ws.`create_time`) time
FROM `t_wallet` w
LEFT JOIN `t_wallet_snapshot` ws
ON w.`id` = ws.`wallet_id`
WHERE ws.type = 4
AND ws.status = 0
GROUP BY w.`shop_id`
ORDER BY time) temp
ON s.id = temp.`shop_id`
ORDER BY temp.time DESC
我已经有了这样的实体,例如Shop.class,Wallet.class和WalletSnapshot.class:
@Getter
@Setter
@Entity
@NoArgsConstructor
@Table(name = "t_shop")
@FieldDefaults(level = AccessLevel.PRIVATE)
public class Shop implements Serializable {
@Id
@GeneratedValue
Integer id;
@Column(nullable = false)
String name;
@OneToMany(mappedBy = "shop", fetch = FetchType.LAZY)
List<Wallet> wallets;
}
我的存储库是这样的:
public interface ShopRepository extends JpaRepository<Shop, Integer>, JpaSpecificationExecutor<Shop> {
}
服务中的
:public List<ShopDTO> getAll(ShopQuery shopQuery, Sort sort) {
return this.shopRepository.findAll(ShopSpec.spec(shopQuery, false), sort).stream().map(ShopDTO::new)
.collect(Collectors.toList());
}
现在,我想知道如何在ShopSpec中编写我的代码以对像sql这样的商店进行排序:
public interface ShopSpec {
static Specification<Shop> spec(ShopQuery shopQuery, Boolean checkUnique) {
return (root, query, cb) -> {
query.distinct(true);
List<Predicate> predicates = new ArrayList<>();
if (shopQuery.getId() != null) {
if (checkUnique != null && checkUnique) {
predicates.add(cb.notEqual(root.get("id"), shopQuery.getId()));
} else {
predicates.add(cb.equal(root.get("id"), shopQuery.getId()));
}
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
};
}
}
这是我第一次发布问题。我已经尽力描述了我的问题。