简体   繁体   中英

spring data jpa filter children in @OneToMany


I have a EmployeeTest entity which is parent and FunGroupInfo entity which is child. both these two entities are mapped by employeeId . I need a way to filter out the child entities which matches the search condition, so that the result will contain only parent and child(which meets requirement).

EmployeeTest class:

@Entity(name = "EmployeeTbl")
public class EmployeeTest{
 @Id
 @Column(name = "emp_id")
 private String employeeId;

 @OneToMany(mappedBy= "employeeId", fetch =FetchType.Eager)
 private Set<FunGroupInfo> funGroupInfo;
}

FunGroupInfo class:

@Entity(name = "FunGroupTbl")
public class FunGroupInfo{
 @Id
 @Column(name = "group_id")
 private String groupId;

 @Column(name = "emp_id")
 private String employeeId;

 @Column(name = "type_id")
 private String typeId;

 @Column(name = "active")
 private String activeFlag;

}

EmpRepository Interface:

@Repository
public interface EmpRepository extends JpaRepository<EmployeeTest, String>{
List<EmployeeTest> findByFunGroupInfoTypeId(String typeId)
}

//inside by test method

@Autowired 
private EmpRepository  empRepository;

List<EmployeeTest> empList = empRepository.findByFunGroupInfoTypeId("2");

Above line returns me List with FunGroupInfo where typeId are in 1, 2, 3, 4, 5 but i need to get the only the matching FunGroupInfo with typeId 2 info

Result which i get now我现在得到的结果but i actually need only the highlighted one along with parent

If you are using Hibernate , you can use the annotation @Where to filter elements on the OneToMany relationship.

Example:

  import org.hibernate.annotations.Where;
  ...
  @OneToMany(fetch = FetchType.EAGER, mappedBy = "employeeId", cascade = CascadeType.ALL)
  @Where(clause = "type_id = '2'")
  private Set<FunGroupInfo> funGroupInfo;
  ...

More information can be consulted here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM