You*_*sef 1 spring spring-data
我使用spring数据,我觉得非常有趣,但有一个问题,我想要一个通用的方式来搜索实体的领域.
我有一个有很多领域的实体
public class Lostcard implements java.io.Serializable {
private Integer id;
private String nom;
private String prenom;
private String cin;
@DateTimeFormat(pattern = "MM/dd/yyyy")
private Date dateDeclaration;
@DateTimeFormat(pattern = "MM/dd/yyyy")
private Date dateDuplicata;
private String annexeAdmin;
[...]
Run Code Online (Sandbox Code Playgroud)
所以我想这样做:
public interface LostcardRepository extends JpaRepository<Lostcard, Integer> {
List<Lostcard> findByNom(String nom);
List<Lostcard> findByPrenom(String prenom);
List<Lostcard> findByCin(String cin);
[...]
}
Run Code Online (Sandbox Code Playgroud)
有没有像findByProperty(String属性,Object value)这样的通用方法?
我认为最简单的方法是使用规范.您必须使您的接口扩展JpaSpecificationExecutor,然后您可以使用您自己的规范来执行查询.
public interface LostcardRepository extends JpaRepository<Lostcard, Integer>, JpaSpecificationExecutor<Lostcard> {
...
}
Run Code Online (Sandbox Code Playgroud)
然后实现类似下面的类:
public class PropertySpecifications {
public static Specification<Lostcard> byProperty(final String propertyName, final Object propertyValue) {
return new Specification<Lostcard>() {
@Override
public Predicate toPredicate(Root<Lostcard> candidateRoot, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.equal(candidateRoot.get(propertyName), propertyValue);
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以执行查询:
lostcardRepository.findAll(Specifications.where(PropertySpecifications.byProperty("property", "value")));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
869 次 |
| 最近记录: |