【问题标题】:Using Hibernate to pull records based on the number of records in another table使用Hibernate根据另一个表的记录数拉取记录
【发布时间】:2010-08-18 20:56:09
【问题描述】:

我有一个用户表,其中包含两种不同类型的用户(A 和 B)。 A 类用户可以与 B 类用户建立关系(记录在关系表中)。 A 类用户可以与 B 类用户建立的关系数记录在另一个表的一个字段中。

我想让 Hibernate 返回所有未建立所有关系的 A 类用户。我有一个 SQL 查询可以做到这一点。我需要做什么?

编辑

我已经设法通过将我的查询放入 session.createSQLQuery() 中来完成这项工作,但是在所有这些中肯、令人敬畏的休眠代码中包含一个 SQL 块似乎很奇怪。我想,如果可能的话,我宁愿把它放在 HSQL 或 Hibernate 对象中。

这是我试图转换为 HSQL 的伪查询:

select userId 
from (
  select user_id, max_mentees, count(connection_id) num_mentees 
  from user_table 
  join mentor on mentor_id = user_id and user_status = 'ACTIVE'
  left join connections on connection_mentor_id = mentor_id 
    and connection_status = 'ACTIVE' and connection_end > sysdate 
  group by user_id, max_mentees, connection_id
)
where (max_mentees > num_mentees) 
group by user_id

【问题讨论】:

  • I want to have Hibernate return all type A users that do not have all of their relationships established 什么时候?什么时候做什么?
  • 基本上,A 用户将成为 B 用户的导师,而 A 用户一次可以拥有多少“导师”是有限制的。计数是看有多少B(被指导者)用户分配给了A(指导者)用户,以便我们可以将其与另一个表中的限制数量进行比较。

标签: java sql hibernate


【解决方案1】:

这可能会有所帮助:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#querysql-load

我知道您可以在映射文件中执行此操作;不确定它如何与注释一起使用。

【讨论】:

    【解决方案2】:

    假设您有一个 Mentor 类与 MentorRelationship 类具有一对多关系,您将执行以下操作:

    session.createQuery("from Mentor mentor where mentor.menteeRelationships.size < mentor.menteeRelationships.maxNumberOfRelationships")
    

    【讨论】:

      【解决方案3】:

      我想让 Hibernate 返回所有未建立所有关系的 A 类用户。我有一个 SQL 查询可以做到这一点。我需要做什么?

      老实说,您的问题仍然很不清楚(至少对我而言),并且没有看到 SQL,没有看到您的对象模型和映射,这似乎很难准确,我的建议是:

      • 将 SQL 转换为 HQL ~or~
      • Native Query 运行您的查询

      如果您希望得到更详细的答案,您应该 IMO 提供更多详细信息。

      【讨论】:

      • 我已经用我想要重现的查询更新了我的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2023-04-08
      • 2021-07-13
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多