I have a method that returns an Employee by Id with a simple entitymanager.find(id) but now I need to find an employee by id that has a salary assigned to it, (the classes Employee and Salary are mapped through OneToMany), should I use an entityManager.find() or entityManager.createQuery()?
@Override
public Optional<Employee> findById(Long emptNo) {
try {
return Optional.ofNullable(this.entityManager.find(Employee.class, emptNo));
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
}
This is where i need help:
@Override
public Optional<Employee> findByIdWithSalary(Long empNo) {
this.entityManager.createQuery("select (e.empNo,s.salary,s.fromDate,s.toDate) as from employees e, salaries s where e.empNo=s.empNo");
try {
return Optional.ofNullable(this.entityManager.find(Employee.class, empNo));
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
}
CodePudding user response:
you need to change the query like below.
@Override
public Optional<Employee> findByIdWithSalary(Long empNo) {
this.entityManager.createQuery("select * from employees e left join e.empNo=s.empNo where s.salary >0");
try {
return Optional.ofNullable(this.entityManager.find(Employee.class, empNo));
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
}
if it does not working send your entity classes. we can do the same with that also.
