【问题标题】:How to conditionally WHERE populated foreign keys with OneToMany Entity?如何有条件地使用 OneToMany 实体填充外键?
【发布时间】:2019-10-13 00:20:54
【问题描述】:

我假设设置如下:https://howtodoinjava.com/hibernate/hibernate-one-to-many-mapping-using-annotations/

员工:

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

帐号:

@ManyToOne
private EmployeeEntity employee;

使用 JPA/Hibernate,如何使用适用于 Account 的 WHERE 条件获取结果。换句话说,查询类似Select all employees with accounts with sales &gt; 0 或类似的内容。

【问题讨论】:

  • 帐户表中的销售列在哪里?
  • @Abhijeet sales 列将是帐户表中的数字值(INT,...)

标签: java spring hibernate jpa criteria


【解决方案1】:

我假设帐户表中的销售列为 INT。

您可以编写如下查询:

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();

我建议您阅读本教程以了解 Hibernate 关联中的 CRUD 操作 https://www.dineshonjava.com/spring-crud-example-using-many-to-one/

【讨论】:

  • 自写字符串查询生成查询时,是否还可以使用.setFirstResult.setMaxResults等方法?
  • 是的。这是可能的。 query.setFirstResult(0); query.setMaxResults(5); 这样然后调用getResultList 方法
  • @janniks 我建议你阅读这个dineshonjava.com/spring-crud-example-using-many-to-one 教程
  • 是否也可以使用标准生成器而不是TypedQuery 来实现相同的功能?
  • 是的,有可能。您也可以使用标准@janniks
猜你喜欢
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
  • 2023-03-31
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多