在Spring Data JPA中过滤了记录

问题描述 投票:0回答:1

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

员工实体

 @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

每当我试图通过弹簧数据获取实体时

public EmployeeInfo findByEmployeeId(int employeeId)

它返回了四个地址的结果。有没有办法在条件的基础上获得地址

例如

select * from employeeInfo where address ="homeAddress" and employeeId =1;
spring-data-jpa spring-data jpql hibernate-onetomany
1个回答
1
投票

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

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

或者你可以利用'Spring Data存储库查询派生机制'并在你的AddressRepository中添加这个方法:

Address findByAddressTypeAndEmployeeId(String type, Integer id)

编辑

如果您需要其他字段/数据,可以使用DTO。

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

并在你EmployeeRepository创建这个DTO

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

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

© www.soinside.com 2019 - 2024. All rights reserved.