Spring Data JPA规范使用具有一对多关系的标准构建器

2022-09-03 13:30:47

我有一个实体,一个实体和一个实体。UserUserToApplicationApplication

单个可以访问多个 .一个可以被多个使用。UserApplicationApplicationUser

下面是实体。User

@Entity
@Table(name = "USER", schema = "UDB")
public class User {
    private Long userId;
    private Collection<Application> applications;
    private String firstNm;
    private String lastNm;
    private String email;

    @SequenceGenerator(name = "generator", sequenceName = "UDB.USER_SEQ", initialValue = 1, allocationSize = 1)
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
    @Column(name = "USER_ID", unique = true, nullable = false)
    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    public Collection<Application> getApplications() {
        return applications;
    }

    public void setApplications(Collection<Application> applications) {
        this.applications = applications;
    }

    /* Other getters and setters omitted for brevity */
}

下面是实体。UserToApplication

@Entity
@Table(name = "USER_TO_APPLICATION", schema = "UDB")
public class Application {
    private Long userToApplicationId;
    private User user;
    private Application application;

    @SequenceGenerator(name = "generator", sequenceName = "UDB.USER_TO_APP_SEQ", initialValue = 0, allocationSize = 1)
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
    @Column(name = "USER_TO_APPLICATION_ID", unique = true, nullable = false)
    public Long getUserToApplicationId() {
        return userToApplicationId;
    }

    public void setUserToApplicationId(Long userToApplicationId) {
        this.userToApplicationId = userToApplicationId;
    }

    @ManyToOne
    @JoinColumn(name = "USER_ID", referencedColumnName = "USER_ID", nullable = false)
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @ManyToOne
    @JoinColumn(name = "APPLICATION_ID", nullable = false)
    public Application getApplication() {
        return application;
    }
}

这是实体。Application

@Entity
@Table(name = "APPLICATION", schema = "UDB")
public class Application {
    private Long applicationId;
    private String name;
    private String code;

    /* Getters and setters omitted for brevity */
}

我有以下用于搜索 by、 和 .SpecificationUserfirstNmlastNmemail

public class UserSpecification {

    public static Specification<User> findByFirstNmLastNmEmail(String firstNm, String lastNm, String email) {
        return new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                final Predicate firstNmPredicate = null;
                final Predicate lastNmPredicate = null;
                final Predicate emailPredicate = null;

                if (!StringUtils.isEmpty(firstNm)) {
                    firstNmPredicate = cb.like(cb.lower(root.get(User_.firstNm), firstNm));
                }
                if (!StringUtils.isEmpty(lastNm)) {
                    lastNmPredicate = cb.like(cb.lower(root.get(User_.lastNm), lastNm));
                }
                if (!StringUtils.isEmpty(email)) {
                    emailPredicate = cb.like(cb.lower(root.get(User_.email), email));
                }
                return cb.and(firstNmPredicate, lastNmPredicate, emailPredicate);
            }
        };
    }

}

这是我到目前为止拥有的元模型。User_

@StaticMetamodel(User.class)
public class User_ {
    public static volatile SingularAttribute<User, String> firstNm;
    public static volatile SingularAttribute<User, String> lastNm;
    public static volatile SingularAttribute<User, String> email;
}

现在,我还想将应用程序 ID 列表传递给 ,以便其方法签名为:Specification

public static Specification<User> findByFirstNmLastNmEmailApp(String firstNm, String lastNm, String email, Collection<Long> appIds)

所以,我的问题是,如果我将映射添加到实体字段的元模型,那么我如何在?@OneToManyUser_Collection<Application> applicationsUserSpecification

我的当前查询类似于以下 SQL 查询:Specification

select * from user u
where lower(first_nm) like '%firstNm%'
and lower(last_nm) like '%lastNm%'
and lower(email) like '%email%';

我想在新作品中实现的将是这样的:Specification

select * from user u
join user_to_application uta on uta.user_id = u.user_id
where lower(u.first_nm) like '%firstNm%'
and lower(u.last_nm) like '%lastNm%'
and lower(u.email) like '%email%'
and uta.application_id in (appIds);

是否可以在元模型中进行这种映射,以及如何在我的?Specification


答案 1

我找到了一个解决方案。为了映射一对多属性,在元模型中,我添加了以下内容:

public static volatile CollectionAttribute<User, Application> applications;

我还需要为实体添加一个元模型。Application

@StaticMetamodel(Application.class)
public class Application_ {
    public static volatile SingularAttribute<Application, Long> applicationId;
}

然后在我的 中,我可以使用实例上的方法为用户访问 。这是我形成的。Specificationapplications.join()Root<User>Predicate

final Predicate appPredicate = root.join(User_.applications).get(Application_.applicationId).in(appIds);

另外,值得注意的是,如果任何输入值为空,则问题中编写的我的输入值将不起作用。传递给 方法的 null 将导致 .因此,我创建了一个 类型 ,然后如果相应的参数不为空,则将每个添加到列表中。最后,我将 转换为数组以将其传递给 .这是最终的:SpecificationPredicate.and()CriteriaBuilderNullPointerExceptionArrayListPredicatePredicateArrayList.and()CriteriaBuilderSpecification

public class UserSpecification {

    public static Specification<User> findByFirstNmLastNmEmailApp(String firstNm, String lastNm, String email, Collection<Long> appIds) {
        return new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                final Collection<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(firstNm)) {
                    final Predicate firstNmPredicate = cb.like(cb.lower(root.get(User_.firstNm), firstNm));
                    predicates.add(firstNmPredicate);
                }
                if (!StringUtils.isEmpty(lastNm)) {
                    final Predicate lastNmPredicate = cb.like(cb.lower(root.get(User_.lastNm), lastNm));
                    predicates.add(lastNmPredicate);
                }
                if (!StringUtils.isEmpty(email)) {
                    final Predicate emailPredicate = cb.like(cb.lower(root.get(User_.email), email));
                    predicates.add(emailPredicate);
                }
                if (!appIds.isEmpty()) {
                    final Predicate appPredicate = root.join(User_.applications).get(Application_.applicationId).in(appIds);
                    predicates.add(appPredicate);
                }

                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }

}

答案 2

推荐