Jpa + Hibernate连接获取返回不一致的数据

时间:2016-06-24 11:55:44

标签: java hibernate jpa

我们正在通过JPA + Hibernate 4执行一个返回一些不一致数据的查询。

我们有一个“父”表:

PARENT
    id *
    req_num
    active
    creation_date

和一个“孩子”表:

CHILD
    id *
    type
    name
    email

一个父母可以拥有多个孩子,并使用另一个表格映射到数据库中:

PARENT_CHILDS
    parent_id (FK to PARENT)
    child_id (FK to CHILD)
    child_order

在Java中,我们的Parent类有一个名为childs的@OneToMany注释列表。它们都用@Entity注释。 我们使用org.hibernate.cfg.ImprovedNamingStrategy作为我们的命名策略。

我们正在执行的查询是:

select parent from Parent parent join fetch parent.childs child where child.type IN ('01', '02') and child.email = 'mail@mail.com' and parent.active = 1 and parent.reqNum != 'testReqNum'

这被转换为下一个纯SQL查询(我们使用show_sql = true属性看到这个):

select parent0_.id as id2_, parent0_.active as active2_, parent0_.creation_date as creation2_
    from parent parent0_ 
    inner join parent_childs childs1_ on parent0_.id=childs1_.Application_id 
    inner join child child2_ on childs1_.child_id=child2_.id 
    where (child2_.type in (? , ?)) and child2_.email=? and parent0_.active=? and parent0_.req_num<>? 

我们的父表只有2个父母满足条件“parent0_.active =?and parent0_.req_num&lt;&gt;?”。他们每个人都有两个孩子。并且只有他们的一个孩子满足条件“((?,?)中的child2_.type和child2_.email =?”。

因此,当我们直接对Oracle数据库执行SQL查询时,它只返回2行(2个父项,每个只有一个子项)。

然而,在Java中我们正在恢复一些奇怪的结果,如果我们使用“内部联接”,“加入”或“加入获取”,则会有所不同。例如,我们收到了三个父母的名单。一个有一个孩子,另一个有另一个孩子,不满足邮件条件,最后一个有两个孩子。

我们想知道为什么我们会遇到这种行为,更重要的是,我们如何解决这个问题呢?

感谢。亲切的问候。

1 个答案:

答案 0 :(得分:0)

正如我在评论中提到的,实现您的解决方案不需要多对多的关系。此外,您的链接表不是正确的链接表,因为它有自己的ID,因此必须被视为另一个实体。

如果您无法更改数据库架构,则可以通过以下方式实现实体之间的关系:

  • OneToManyParent
  • 之间的ParentChild关系
  • OneToOneParentChild
  • 之间的Child关系