@OneToMany

时间:2019-07-14 06:17:56

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


我有一个为父级的 EmployeeTest 实体和一个为子级的 FunGroupInfo 实体。这两个实体均。我需要一种方法来筛选出符合搜索条件的子实体,以便结果将仅包含父项和子项(满足要求)。

EmployeeTest类:

@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类:

@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接口:

@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");

上一行返回给我带有FunGroupInfo的列表,其中typeId在1,2,3,4,5,但我需要获取唯一匹配的具有typeId 2 info的FunGroupInfo

我现在得到Result which i get now的结果,但实际上我只需要将突出显示的结果与父项一起

1 个答案:

答案 0 :(得分:0)

如果使用的是 Hibernate ,则可以使用注释 @Where 来过滤 OneToMany 关系中的元素。

示例:

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

更多信息,请咨询here