Spring Data Repositiories - 为每个查询添加特定参数

Olg*_*zek 6 java spring mongodb spring-data spring-data-mongodb

我有一些扩展的存储库org.springframework.data.mongodb.repository.MongoRepository。我添加了一些通过不同参数搜索实体的方法,但是,在任何搜索中,我只想搜索字段设置为activetrue已选择标记为而active=false不是删除)的实体。例如,两个示例存储库将如下所示:

interface XxRepository extends MongoRepository<Xx, String> {

    Optional<Xx> findOneByNameIgnoreCaseAndActiveTrue(String name)

    Page<Xx> findByActiveTrue(Pageable pageable)

    Xx findOneByIdAndActiveTrue(String id)

}

interface YyRepository extends MongoRepository<Yy, String> {

    Optional<Yy> findOneByEmailAndActiveTrue(String email)
}
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以让我不向每个方法添加byActiveTrue\并将其设置在一个位置的某个位置以用于所有查询?andActiveTrue

Zor*_*ube 1

您可以使用 Criteria 将模板查询写入 MongoRepository。例子

class abstract MongoRepository<W, X> {

    protected Class<W> typeOfEntity;
    private Class<X> typeOfId;

    public MongoRepository() {
        typeOfEntity = (Class<W>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        typeOfId = (Class<X>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public W get(X id) throws Exception {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<W> q = cb.createQuery(typeOfEntity);
        Root<W> r = q.from(typeOfEntity);

        String idName = CommonEntity.findIdFieldName(typeOfEntity);
        Predicate andClose = cb.and(cb.equal(r.get("active"), true));

        q.where(cb.equal(r.get(idName), id), andClose);

        return em.createQuery(q).getSingleResult();
    }
}
Run Code Online (Sandbox Code Playgroud)

之后,您可以对对象运行方式和定型保持信心,以运行良好的请求类型。

findIdFieldName是一种使用@Id 来获取id 字段名称的方法。

public abstract class CommonEntity implements Serializable {

    public static String findIdFieldName(Class cls) {
        for (Field field : cls.getDeclaredFields()) {
            String name = field.getName();
            Annotation[] annotations = field.getDeclaredAnnotations();
            for (int i = 0; i < annotations.length; i++) {
                if (annotations[i].annotationType().equals(Id.class)) {
                    return name;
                }
            }
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)