【问题标题】:HQL impossible to read attribute which is an instance of subclassHQL 无法读取作为子类实例的属性
【发布时间】:2014-05-01 23:03:09
【问题描述】:

首先,我想说的是,我已经阅读了数十篇关于使用 hibernate 进行继承映射或多态获取的文章,但没有找到解决问题的方法。 虽然情况很简单。

执行以下代码时: 列出餐点 = sessionFactory.getCurrentSession() .createQuery("select m from Meal m").list(); 我收到以下错误: org.hibernate.WrongClassException:ID 为 1 的对象不属于指定的子类:com.myPack.Fruit(鉴别器:橙色)

实际上,我看不懂 Orange 或 Apple 中的抽象类fruit

一餐包含水果,可以是橙子或苹果

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "fruit")
public abstract class Fruit {

    @Id
    @GeneratedValue
    @Column(name = "id", unique = true)
    private Integer id;
}

@Entity(name = "Orange") //this is the discriminatorValue stored in dtype column
public class Orange extends Fruit {
}

@Entity(name = "Apple") //this is the discriminatorValue stored in dtype column
public class Orange extends Fruit {
}

@Entity
@Table(name = "meal")
public class Meal {
    ...

    @ManyToOne
    @JoinColumn(name = "fruit_id", nullable = false)
    private Fruit fruit  = null;
}

获取不是 LAZY,所以我不应该对代理有任何问题。 我不明白为什么休眠无法发现这样的水果是橙子或苹果,因为水果表在 DTYPE 列中包含鉴别器橙子或苹果

如果能解决这个问题,我将不胜感激。 (对不起我含糊的英语)

。 .

经过进一步研究,我发现@DiscriminatorOptions(force = true) 可以解决我的问题,但最终……无奈。 我了解到的是,即使 hibernate 拥有所有信息来查找具体类,在某些情况下也需要像 @DiscriminatorOptions(force = true) 这样的注释。 无论如何,我想告诉休眠:“嘿休眠不要尝试实例化抽象水果类,因为它是抽象的。嘿休眠尝试依赖设置了@DiscriminatorValue 的实体”..但是休眠是聋的:(

【问题讨论】:

    标签: hibernate inheritance polymorphism hql subclass


    【解决方案1】:

    我在使用 Spring 4.0.2 和 Hibernate 4.3.4 时遇到了完全相同的问题。我认为我的项目的依赖项中缺少一些东西,或者可能只是 Hibernate 中的一个错误。

    我建议你回滚你的 Hibernate 版本,我拥有的最后一个工作版本是 4.2.4,我正在恢复到。

    【讨论】:

    • 将 fom 4.1.0.Final hibernate 版本更改为 4.2.4 或 4.3.4 版本的行为是不同的,但在这两种情况下问题仍然存在:在 4.1.0.Final createQuery("select m from Meal m") 暗示 4.2.4 或 4.3.4 createQuery("select m from Meal m") 暗示没有例外但 Meal 的属性fruit 为空。毕竟在功能上是同一个问题。
    【解决方案2】:

    替换这个试试

    List meals = sessionFactory.getCurrentSession().createQuery("from Meal").list();
    

    【讨论】:

    • 将 fom createQuery("select m from Meal m") 更改为 createQuery("from Meal") 在 4.1.0.Final hibernate 版本中无效。但移动到 4.2.4 或 4.3.4 版本时,行为有所不同,但在这两种情况下,问题仍然存在:
    • createQuery("from Meal") 暗示异常 createQuery("select m from Meal m") 暗示没有异常,但 Meal 的属性fruit 为空。毕竟在功能上是同一个问题。
    猜你喜欢
    • 1970-01-01
    • 2012-09-24
    • 2021-11-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2021-11-28
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多