Hibernate LEFTJOIN没有为@ManyToOne反身关系生成

时间:2016-03-29 17:26:09

标签: hibernate left-join many-to-one joincolumn

我有一张反身关联的表:

容器可以与父级关联(Column container_id)。 容器可以将容器作为子容器。

@Entity
public class Container implements Serializable {

  @ManyToOne
  @JoinColumn(name = "container_id", nullable = true, referencedColumnName = "original_id")
  private Container containedIn;

  @Column(name = "original_id")
  private long originalId;

  @OneToMany(mappedBy = "containedIn")
  private List<Container> contains = new ArrayList<>();

... 

问题:

生成的请求是:

  Hibernate: select * from ( 
  select *  
  from container con0_, container con1_ 
  where con0_.container_id=con1_.original_id 
  order by con1_.code ) where rownum <= ?

我期待左外连接:

from container con0_ left outer join container con1_ 
      on con0_.container_id=con1_.original_id.

未检索到没有父(Root Box CON0000007)的容器,因为Hibernate不生成左连接:

ID | ORIGINAL_ID |代码| TYPE | CONTAINER_ID(父母)

1 | 2 | CON000000002 |套餐| 12

2 | 4 | CON000000004 |套餐| 10

4 | 6 | CON000000006 |套餐| 11

5 | 8 | CON000000008 |套餐| 10

7 | 10 | CON0000002 |盒子| 15

8 | 11 | CON0000003 |盒子| 15

9 | 12 | CON0000004 |盒子| 15

12 | 15 | CON0000007 |根盒子| NULL

1 个答案:

答案 0 :(得分:0)

该模型似乎很好。看起来您没有在查询中加载子级别。并且默认情况下你有延迟加载,所以hibernate不会查询子项。如果是这种情况,请查看示例Hibernate: best practice to pull all lazy collections