janniks
janniks

Reputation: 3180

How to conditionally WHERE populated foreign keys with OneToMany Entity?

I am assuming a setup as described in: https://howtodoinjava.com/hibernate/hibernate-one-to-many-mapping-using-annotations/

one to many relation

Employee:

@JoinColumn(name="EMPLOYEE_ID")
private Set<AccountEntity> accounts;

Account:

@ManyToOne
private EmployeeEntity employee;

Using JPA/Hibernate, how can I fetch results using a WHERE condition that applies to Account. In other words, query something like Select all employees with accounts with sales > 0 or similar.

Upvotes: 0

Views: 439

Answers (1)

Abhijeet
Abhijeet

Reputation: 4309

I'm assuming sales column as INT in account table.

you can write a query like following:

TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e JOIN Account a ON e.id = a.accounts.employee_id WHERE a.sales > :sales", Employee.class);
query.setParameter("sales", salesInput);
List<Employee> items = query.getResultList();

I would recommend you to go through this tutorial to learn about CRUD operations in Hibernate Associations https://www.dineshonjava.com/spring-crud-example-using-many-to-one/

Upvotes: 1

Related Questions