【问题标题】:Left outer join fetch doesn't fill map collection properly (HQL)左外连接提取未正确填充地图集合(HQL)
【发布时间】:2009-05-28 11:06:55
【问题描述】:

我有这样的映射类:

@Entity
public class CurrencyTable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @Version
    @Column(nullable=false)
    private Timestamp version;

    @Column(length=32, unique=true)
    private String refCode;

   @OneToMany(mappedBy="currencyTable", fetch=FetchType.LAZY, cascade =  {CascadeType.ALL})
   @MapKey(name="currency")
   private Map<String, CurrencyTableRate> rateMap = new HashMap<String, CurrencyTableRate>();
}

@Entity
public class CurrencyTableRate{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @Version
    @Column(nullable=false)
    private Timestamp version;

    @Column(length=3)
    private String currency;

    @Basic
    private BigDecimal rateValue;

    @ManyToOne(optional=false,fetch=FetchType.LAZY)
    private CurrencyTable currencyTable;
}

CurrencyTable中有一行,CurrencyTableRate中有3行引用数据库中的CurrencyTable。

当我使用 HQL 加载 CurrencyTable 时:

from CurrencyTable where refCode = :refCode

我在 rateMap 中得到一个包含三个条目的实体,但如果我尝试这个:

from CurrencyTable table left outer join fetch table.rateMap where refCode = :refCode

rateMap 中只有一个条目。

我查看了 Hibernate 生成的查询并手动运行它 - 它返回了三行,正如预期的那样,因此在获取后映射它们似乎是一个问题。有没有人遇到过这样的问题? 我使用 Hibernate 版本 3.2.6.ga 和 Oracle 10g

【问题讨论】:

  • 我有同样的问题,找不到解决办法。我的查询有时不起作用并抛出了lazyInitializationException

标签: hibernate join map one-to-many


【解决方案1】:

首先我建议你给 refCode 添加一个别名。我认为这不会对结果产生影响,但以防万一。

from CurrencyTable table left outer join fetch table.rateMap where table.refCode = :refCode

其次,打开您的 SQL 代码并分析 SQL 级别的实际情况。在这种情况下,我对 HQL 也有类似的问题

from CurrencyTable table left outer join fetch table.rateMap map where map.id = :id

我必须重写

from CurrencyTable table left outer join fetch table.rateMap map where EXISTS (SELECT a.id from CurrencyTable table a INNER JOIN a.rateMap m WHERE m.id = :id and table.id=a.id)

希望我的提示会有所帮助。

【讨论】:

  • 我添加了别名,但没有影响。正如我所写的那样,我查看了 Hibernate 生成的 SQL 查询并手动运行它——它返回了三行,正如预期的那样。我使用了一种解决方法,即运行第一个查询(没有左外连接获取),然后在地图上调用 Hibernate.initialize。由于在我的工作中,我没有时间调试 Hibernate 以了解发生了什么,但这种行为让我感到不安:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
相关资源
最近更新 更多