Spring CRUDRepository findBy 多个字段

Spring CRUDRepository findBy Multiple fields

如果我的 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'

您可以使用 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);

Please consult also the Spring Data JPA reference manual for further features.