Spring CRUDRepository findBy多个字段

时间:2019-03-27 12:14:53

标签: spring-boot spring-data-jpa crud

如果我的EmployeeEntity包含多个字段:

first_name
last_name
department
office_name
state,
etc..

有没有一种方法可以让我的CRUDRepository接口中只有一个find ...()接口,可以根据查询参数搜索雇员而无需对该接口进行硬编码?

http://localhost:8080/employees?last_name='me'&state='tx'

http://localhost:8080/employee?state='tx'&office_name='alpha'

1 个答案:

答案 0 :(得分:1)

您可以使用QueryDSL根据您的实体字段在存储库中动态生成任何查询。

要将其与Spring Data JPA集成,请在项目中添加以下两个依赖项和JPA注释处理器:

<dependency> 
    <groupId>com.querydsl</groupId> 
    <artifactId>querydsl-apt</artifactId> 
    <version>4.1.4</version>
    </dependency>
<dependency> 
    <groupId>com.querydsl</groupId> 
    <artifactId>querydsl-jpa</artifactId> 
    <version>4.1.4</version> 
</dependency>

<plugin>
    <groupId>com.mysema.maven</groupId>
    <artifactId>apt-maven-plugin</artifactId>
    <version>1.1.3</version>
    <executions>
        <execution>
            <goals>
                <goal>process</goal>
            </goals>
            <configuration>
                <outputDirectory>target/generated-sources/java</outputDirectory>
                <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
            </configuration>
        </execution>
    </executions>
</plugin>

...并以这种方式扩展您的存储库:

public interface EmployeeRepository extends JpaRepository<EmployeeEntity, Long>, 
  QuerydslPredicateExecutor<EmployeeEntity>, QuerydslBinderCustomizer<QEmployeeEntity> {
}

现在,您可以表达所有类型的查询组合:

BooleanExpression name = QEmployeeEntity.employeeEntity.last_name.eq("brawn");
BooleanExpression stateAndName = QEmployeeEntity.employeeEntity.state.eq("tx").and(name);
  

也请咨询 Spring Data JPA reference manual以获取更多功能。