为 QueryDSL 支持自定义参数绑定 [英] Customizing Param Binding for QueryDSL Support

查看:51
本文介绍了为 QueryDSL 支持自定义参数绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Spring Data Rest 存储库,它利用了此处概述的 QueryDSL 支持:

I have a Spring Data Rest repository which utilises the QueryDSL support outlined here:

https://spring.io/blog/2015/09/04/what-s-new-in-spring-data-release-gosling#spring-data-rest

默认是使用equals查询所有指定的参数.同一篇文章中提供了一种将 param 绑定覆盖为除 equals 以外的其他内容的机制,但它需要 Java 8.

The default is to query all specified parameters using equals. A mechanism to override the param binding to something other than equals is given in the same article however it requires Java 8.

https://spring.io/blog/2015/09/04/what-s-new-in-spring-data-release-gosling#querydsl-web-support

Java 7 中是否有任何干净的方法来实现相同的功能?

Is there any clean way in Java 7 to achieve the same functionality?

我可以让绑定自定义工作如下:

I can get the binding customization working as below:

@Override
public void customize(QuerydslBindings bindings, QMember member) {
    bindings.bind(member.forename).first(new SingleValueBinding<StringPath, String>() {
        @Override
        public Predicate bind(StringPath path, String value) {
            return path.like(value);
        }
    });

    bindings.bind(member.surname).first(new SingleValueBinding<StringPath, String>() {
        @Override
        public Predicate bind(StringPath path, String value) {
            return path.startsWith(value);
        }
    });
}

然而,这些示例都使用存储库接口上的 Java 8 默认方法来应用它们.

However the examples all use a Java 8 default method on the repository interface to have them applied.

public interface MemberRepository extends JpaRepository<Member, Long>, 
         QueryDslPredicateExecutor<Member>,QuerydslBinderCustomizer<QMember> {

    default void customize(QuerydslBindings bindings, QMember member) {
      ....
    }
}

在 Java 7 中这显然是不可能的.我曾尝试使用自定义存储库,但失败并显示错误:

In Java 7 this is obviously not possible. I have tried with a custom repository however that fails with an error:

org.springframework.data.mapping.PropertyReferenceException:未找到类型成员的属性自定义!

org.springframework.data.mapping.PropertyReferenceException: No property customize found for type Member!

public interface MemberRepositoryCustom {

    public void customize(QuerydslBindings bindings, QMember member);
}

public class MemberRepositoryCustomImpl implements MemberRepositoryCustom {

    @Override
    public void customize(QuerydslBindings bindings, QMember member) {
        bindings.bind(member.forename).first(new SingleValueBinding<StringPath, String>() {
            @Override
            public Predicate bind(StringPath path, String value) {
                return path.like(value);
            }
        });

        bindings.bind(member.surname).first(new SingleValueBinding<StringPath, String>() {
            @Override
            public Predicate bind(StringPath path, String value) {
                return path.startsWith(value);
            }
        });
    }
}

推荐答案

您可以通过两种方式使用 Java 7 完成此操作.第一种方式是创建一个通用基础存储库,将自定义绑定应用于所有已实现的模型存储库.例如:

There are two ways that you can accomplish this using Java 7. The first way is to create a generic base repository that will apply the custom bindings to all of the implemented model repositories. For example:

public class GenericModelRepository<T, ID extends Serializable, S extends EntityPath<T>> extends QueryDslJpaRepository<T, ID> implements QuerydslBinderCustomizer<S> {

    public GenericModelRepository(
            JpaEntityInformation<T, ID> entityInformation,
            EntityManager entityManager) {
        super(entityInformation, entityManager);
    }

    public GenericModelRepository(
            JpaEntityInformation<T, ID> entityInformation,
            EntityManager entityManager,
            EntityPathResolver resolver) {
        super(entityInformation, entityManager, resolver);
    }

    @Override 
    public void customize(QuerydslBindings bindings, S t) {
            bindings.bind(String.class).first(new SingleValueBinding<StringPath, String>() {
                @Override 
                public Predicate bind(StringPath path, String s) {
                    return path.equalsIgnoreCase(s);
                }
            });
    }
}

要告诉 Spring Data 在实现所有自定义存储库接口时使用此基础存储库,只需将其添加为 @EnableJpaRepositories 注释中的 repositoryBaseClass:

To tell Spring Data to use this base repository when implementing all of your custom repository interfaces, simply add it as the repositoryBaseClass in the @EnableJpaRepositories annotation:

@Configuration
@EnableJpaRepositories(basePackages = { "me.woemler.project.repositories" }, repositoryBaseClass = GenericModelRepository.class)
@EnableTransactionManagement
public class RepositoryConfig { ... }

@RepositoryRestResource
public interface PersonRepository extends JpaRepository<Person, Long>, 
        QueryDslPredicateExecutor<Person>,
        QuerydslBinderCustomizer<EntityPath<Person>> {
}

现在所有的 Web 服务 StringPath 查询操作都将是不区分大小写的相等性测试:

Now all web service StringPath query operations will be case-insensitive equality tests:

GET http://localhost:8080/persons?name=joe%20smith

    
    "_embedded": {
        "persons": [
          {
            "name": "Joe Smith",
            "gender": "M",
            "age": 35,
            "_links": {
              "self": {
                "href": "http://localhost:8080/persons/1"
              },
              "person": {
                "href": "http://localhost:8080/persons/1"
              }
            }
          }
        ]
      },
      "_links": {
        "self": {
          "href": "http://localhost:8080/persons"
        },
        "profile": {
          "href": "http://localhost:8080/profile/persons"
        }
      },
      "page": {
        "size": 20,
        "totalElements": 1,
        "totalPages": 1,
        "number": 0
      }
    }

第二个选项,如果您想要更精细地控制每个存储库处理其绑定的方式,则创建您希望自定义的存储库的 Impl 版本:

The second option, should you want more fine control over how each repository handling its bindings would be to create an Impl version of the repositories you wish to customize:

 public class PersonRepositoryImpl implements QuerydslBinderCustomizer<EntityPath<Person>> {
    @Override
    public void customize(QuerydslBindings bindings, EntityPath<Person> t) {
        bindings.bind(String.class).first(new SingleValueBinding<StringPath, String>() {
            @Override
            public Predicate bind(StringPath path, String s) {
                return path.equalsIgnoreCase(s);
            }
        });
    }
}
   

然后您可以正常使用 @EnableJpaRepositories 注释,但您必须为您希望自定义的每个存储库接口创建一个 Impl 实例.

You can then use the @EnableJpaRepositories annotation normally, but you must create an Impl instance for each of your repository interfaces that you wish to customize.

这篇关于为 QueryDSL 支持自定义参数绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆