Reputation: 41
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
Upvotes: 2
Views: 4689
Reputation: 4652
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.
Upvotes: 3