在 Spring Data JPA 中过滤记录

filterd records in Spring Data JPA

您好,有两个实体员工详细信息和地址具有一对多关系。

员工实体

 @Entity
 @Table(name = "employeeInfo")
 public class EmployeeInfo { 
   int employeeId;
   String employeeName;

   @OneToMany
   @JoinColumn(name = "employeeId")
   private List<Address> employeeAddress;
 }

地址实体

@Entity
 @Table(name = "address")
 public class Address{ 
 int employeeId;
 String address;
 String landMark;
 String addressType
}

在上面的结构中,员工有多个地址,如

Home address, work address, permanent address current address

每当我试图通过 spring 数据

获取实体时
public EmployeeInfo findByEmployeeId(int employeeId)

它返回给我四个地址的结果。有没有办法根据条件

获取地址

例如

select * from employeeInfo where address ="homeAddress" and employeeId =1;

您基本上想要检索 已知 员工的地址,因此您可以查询 地址 :

select a from address a where a.adressType= :type and a.employeeId = :id

或者您可以利用“Spring 数据存储库查询派生机制” 并在 AddressRepository:

中添加此方法

Address findByAddressTypeAndEmployeeId(String type, Integer id)

编辑

如果您需要其他 fields/data,您可以使用 DTO。

 public class EmployeeAddressInfo{
   String employeeName;
   Address address;
   EmployeeAddressInfo(String employeeName, Address address){
       this.employeeName = employeeName;
       this.address = address;
   }
   //getters setters
 }

并在你里面创建这个 DTO EmployeeRepository

  @Query(select new com.example.EmployeeAddressInfo(employeeName, address)  from employeeInfo  where address.addressType =:type and employeeId =:id)
  EmployeeAddressInfo findAddressInfo(String type, Long id);

或者您可以使用其他类型的 projections