我正在尝试使用 JPA 规范构建动态子查询。如何将谓词添加到子查询并构建它?
例如,我将有 2 个表:User 和 Usercard:
@Entity
@Table(name = "users", schema = "someschema")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String surName;
private String email;
@OneToMany
private List<Usercard> usercardList;
//other methods...
}
和
@Entity
@Table(name = "usercard", schema = "someschema")
public class Usercard {
@Id
private Long id;
private String account;
private String value;
@ManyToOne
private User user;
//other methods...
}
我有我的回购协议:
@Repository
public interface UserRepository extends JpaRepository<User, Long>,
JpaSpecificationExecutor<User> {}
并尝试构建类似的东西:
public List<User> findByPredicate(String email) {
return userRepository.findAll((Specification<User>) (root,
criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
if (email != null) {
predicates.add(criteriaBuilder.and(criteriaBuilder.equal(
root.get("email"), email)));
}
return criteriaBuilder.and(predicates.toArray(new
Predicate[predicates.size()]));
});
}
但是对于带有谓词的子查询。
我试过这样的方法:
public List<User> findByUsercardAccount(String email, String account) {
return userRepository.findAll(new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?>
criteriaQuery, CriteriaBuilder criteriaBuilder) {
Subquery<Usercard> subquery =
criteriaQuery.subquery(Usercard.class);
Root<Usercard> subRoot = subquery.from(Usercard.class);
List<Predicate> predicates = new ArrayList<>();
//predicates for Users table
predicates.add(criteriaBuilder.and(criteriaBuilder.equal(
root.get("email"), email)));
//predicates for Usercard table
因此,我需要一种在几个表中进行动态搜索的方法,我可以在其中为动态查询和动态子查询传递参数。如果有任何帮助,我将不胜感激。
RISEBY
相关分类