Spring Data JPA findBy可选变量

时间:2017-05-18 15:51:47

标签: java rest spring-data spring-data-jpa

我知道我可以通过向我的存储库界面添加方法来进行自定义查询。例如,如果我有Person实体。

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String firstName;
    private String lastName;
    private String gender;
    private String dateOfBirth;

    // All applicable getters and setters
}

我的存储库界面可能如下所示:

    @RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {

    List<Person> findByLastName(@Param("name") String name);

}

但是如果我想搜索所有参数和所有参数组合该怎么办?例如,如果我想搜索:

  • firstName(单独使用)
  • 姓氏(本身)
  • 性别(单独)
  • dateOfBirth(单独)
  • firstName和LastName
  • firstName和gender
  • firstName和dateOfBirth
  • lastName和性别
  • lastName和dateOfBirth
  • 性别和dateOfBirth
  • firstName和lastName and gender
  • firstName和lastName以及dateOfBirth
  • firstName和lastName以及dateOfBirth和性别

这是否意味着我必须在界面中创建所有这些存储库方法。有没有办法可选择地搜索所有参数。

的内容
findBy(String firstName, String lastName, String gender, String dateOfBirth)

如果正在使用REST API,例如,只想搜索firstName和lastName,它将调用

http://localhost/people/search/findBy?firstName=John&firstName=Smith

UPDATE :我能够用一些SQL技巧解决这个问题在PersonRepository接口中我做了类似这样的事情:

@Query("SELECT * FROM person p WHERE ((:firstName IS NULL) OR (:firstName IS NOT NULL AND p.firstName = :firstName)) AND ((:lastName IS NULL) OR (:lastName IS NOT NULL AND p.lastName = :lastName)) AND ((:gender IS NULL) OR (:gender IS NOT NULL AND p.gender = :gender)) AND ((:dateOfBirth IS NULL) OR (:dateOfBirth IS NOT NULL AND p.dateOfBirth = :dateOfBirth )) ")
        Page<Person> findBy(@Param("firstName") String firstName, @Param("lastName") String lastName, @Param("gender") String gender, @Param("dateOfBirth") String dateOfBirth, Pageable page);

终点以这种方式调用http://localhost:8080/people/search/findBy?firstName=John&lastname=&gender=&dateOfBirth=

你应该得到一个名为“John”的所有人的名单

1 个答案:

答案 0 :(得分:0)

利用find by example。 我是为员工做的。

<强> 存储库:

//skipped lines    
import org.springframework.data.domain.Example
//skipped lines
interface EmployeeRepository extends JpaRepository<Employee, EmployeeKey>{
    List<Employee> findAll(Example<Employee> employee);
}

<强> 用法:

// Prepare Employee key with all available search by keys (6 in my case)
EmplyeeKey key = new EmplyeeKey();
key.setField1("field1_value");
key.setField2("field2_value");
//Setting remaining 4 fields

// Create new Employee ans set the search key
Employee employee = new Employee();
employee.setEmployeeKey(key);


// Call the findAll by passing an Example of above Employee object
List<Employee> result = employeeRepository.findAll(Example.of(employee));