【问题标题】:How can one override a method from a Hibernate @MappedSuperclass but keep the originial mapping?如何覆盖 Hibernate @MappedSuperclass 中的方法但保留原始映射?
【发布时间】:2014-02-04 19:32:56
【问题描述】:

我有一个映射的超类,我用它来定义一个方法,它是持久性映射。我正在使用每类表的继承策略。例如这里是一些简单的类继承:

@MappedSuperclass
public class Feline {
    private Long id;
    private String identifier;

    @GeneratedValue(strategy = "GenerationType.AUTO")
    @Id
    public Long getId() {
        return id;
    }

    public String getIdentifier() {
        return identifier;
    }
    // other getters and setters, methods, etc.
}

下一个类不会重写 getIdentifier() 方法,而是将 Cat 的标识符保存在其实体表的“标识符”列中。

@Entity
public class Cat extends Feline {
    private Date dateOfBirth;
    private Set<Kitten> kittens;

    @OneToMany(mappedBy = "mother")
    public Set<Kitten> getKittens() {
        return kittens;
    }
    // other getters and setters, methods, etc.
}

在 Kitten 类中,我想更改标识符以返回 Kitten.identifier + " kitten of " + mohter.getIdentifier() 或例如 "Boots kitten of Ada" 并将此字符串保留在 "identifier" 列中实体的表。

@Entity
public class Kitten extends Cat {
   private Cat mother;

   @ManyToOne
   public Cat getMother() {
       return mother;
   }

   @Override
   public String getIdentifier() {
       return this.getIdentifier() + " kitten of " + mother.getIdentifier(); 
   }
}

当我运行此代码时,我收到一条错误消息“原因:org.Hibernate.MappingException:在 com.example.Kitten 中找到标识符的重复属性映射。”

由于我正在扩展 @Mappedsuperclass,标识符字段应该映射到每个实体表的“标识符”列,但由于某种原因,这不会发生,并且当我覆盖 getIdentifier( ) Kitten 类中的方法。

Cat 和 Kitten 表都有“标识符”列。我不明白如果方法返回正确的类型以映射到同一列,为什么我不能覆盖它。

【问题讨论】:

    标签: java hibernate jpa hibernate-mapping


    【解决方案1】:

    那行不通。但是你可以定义一个鉴别器。

    看看http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/inheritance.html

    【讨论】:

    • 好的,所以我将注释更改为使用鉴别器,现在使用 table-per-sublcas 策略。就像Hibernate Annotations 文档中的示例一样。现在,当我尝试在 sublcas 中覆盖 getIdentifier 方法时,我在实体的映射中得到 org.hibernate.MappingException:com.example.Kitten 列:标识符(应该使用 insert="false" update="false" 进行映射),所以我更改映射并得到相同的错误。不过谢谢你的提示。我觉得我离解决方案更近了。
    • @user2437506 如前所述,您不能覆盖getIdentifier 方法。但是,当您获得Cat 实体时,您可以检查该实体是否为instanceof Kitten,这对您有帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2012-11-29
    • 1970-01-01
    • 2010-11-23
    相关资源
    最近更新 更多