java - 元组列表的 crudrepository findBy 方法签名

标签 java spring collections tuples spring-data-jpa

我有一个像这样的实体类:

@Entity
@Table(name = "CUSTOMER")
class Customer{
    @Id
    @Column(name = "Id")
    Long id;
    @Column(name = "EMAIL_ID")
    String emailId;
    @Column(name = "MOBILE")
    String mobile;
}

如何使用 crudrepository spring data jpa 为以下查询编写 findBy 方法?

select * from customer where (email, mobile) IN (("a@b.c","8971"), ("e@f.g", "8888"))

我期待这样的事情

List<Customer> findByEmailMobileIn(List<Tuple> tuples);

我想从给定的配对中获取客户列表

最佳答案

我认为这可以用 org.springframework.data.jpa.domain.Specification 来完成.您可以传递元组列表并以这种方式处理它们(不要在意元组不是实体,但您需要定义此类):

public class CustomerSpecification implements Specification<Customer> {

    // names of the fields in your Customer entity
    private static final String CONST_EMAIL_ID = "emailId";
    private static final String CONST_MOBILE = "mobile";

    private List<MyTuple> tuples;

    public ClaimSpecification(List<MyTuple> tuples) {
        this.tuples = tuples;
    }

    @Override
    public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        // will be connected with logical OR
        List<Predicate> predicates = new ArrayList<>();

        tuples.forEach(tuple -> {
            List<Predicate> innerPredicates = new ArrayList<>();
            if (tuple.getEmail() != null) {
                 innerPredicates.add(cb.equal(root
                     .<String>get(CONST_EMAIL_ID), tuple.getEmail()));
            }
            if (tuple.getMobile() != null) {
                 innerPredicates.add(cb.equal(root
                     .<String>get(CONST_MOBILE), tuple.getMobile()));
            }
            // these predicates match a tuple, hence joined with AND
            predicates.add(andTogether(innerPredicates, cb));
        });

        return orTogether(predicates, cb);
    }

    private Predicate orTogether(List<Predicate> predicates, CriteriaBuilder cb) {
        return cb.or(predicates.toArray(new Predicate[0]));
    }

    private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
        return cb.and(predicates.toArray(new Predicate[0]));
    }
}

你的仓库应该扩展接口(interface) JpaSpecificationExecutor<Customer> .

然后构造一个包含元组列表的规范并将其传递给方法customerRepo.findAll(Specification<Customer>) - 它返回客户列表。

关于java - 元组列表的 crudrepository findBy 方法签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48032920/

相关文章:

java - 使用 AsyncRestTemplate 多次制作 API 并等待所有完成

java - Spring 中的 Autowiring 与实例化

c# - 具有多个索引的列表

c# - 如何检测集合是否包含特定类型的实例?

java - 根据单选按钮值将值存储在 sqlite 数据库的多个表中

java - Elasticsearch 前缀过滤器

java - 如何在我的 Java Web 应用程序中使用 Alfresco Sharepoint 协议(protocol)

java - 使用 Mockito 在子类中模拟父类

java - Spring 数据休息 : How to search by another object's key?

java - 为什么在 java.util.Collections 中声明静态 java.util.Collections.fill() 方法而不是在 java.util.AbstractList 中声明实例方法?