crudrepository findBy元组列表的方法签名

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

@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@bc","8971"), ("e@fg", "8888")) 

我期待着类似的东西

 List findByEmailMobileIn(List tuples); 

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

我认为这可以通过org.springframework.data.jpa.domain.Specification来完成。 你可以传递一个元组列表并以这种方式继续它们(不要在意Tuple不是一个实体,但是你需要定义这个类):

 public class CustomerSpecification implements Specification { // 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 tuples; public ClaimSpecification(List tuples) { this.tuples = tuples; } @Override public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { // will be connected with logical OR List predicates = new ArrayList<>(); tuples.forEach(tuple -> { List innerPredicates = new ArrayList<>(); if (tuple.getEmail() != null) { innerPredicates.add(cb.equal(root .get(CONST_EMAIL_ID), tuple.getEmail())); } if (tuple.getMobile() != null) { innerPredicates.add(cb.equal(root .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 predicates, CriteriaBuilder cb) { return cb.or(predicates.toArray(new Predicate[0])); } private Predicate andTogether(List predicates, CriteriaBuilder cb) { return cb.and(predicates.toArray(new Predicate[0])); } } 

您的repo应该扩展接口JpaSpecificationExecutor

然后构造一个带有元组列表的规范,并将其传递给方法customerRepo.findAll(Specification) – 它返回一个客户列表。

使用投影可能更干净:

 @Entity @Table(name = "CUSTOMER") class CustomerQueryData { @Id @Column(name = "Id") Long id; @OneToOne @JoinColumns(@JoinColumn(name = "emailId"), @JoinColumn(name = "mobile")) Contact contact; } 

联系实体:

 @Entity @Table(name = "CUSTOMER") class Contact{ @Column(name = "EMAIL_ID") String emailId; @Column(name = "MOBILE") String mobile; } 

在指定实体后,回购:

 CustomerJpaProjection extends Repository, QueryDslPredicateExecutor { @Override List findAll(Predicate predicate); } 

回购电话:

 ArrayList contacts = new ArrayList<>(); contacts.add(new Contact("a@bc","8971")); contacts.add(new Contact("e@fg", "8888")); customerJpaProjection.findAll(QCustomerQueryData.customerQueryData.contact.in(contacts)); 

没有测试过代码。