【问题标题】:Hibernate Annotation using base entity使用基本实体的休眠注释
【发布时间】:2013-09-12 12:28:32
【问题描述】:

在我的项目中,我有一个名为 BaseEntity 的 POJO,如下所示。

class BaseEntity{
    private int id;
    public void setId(int id){
        this.id=id;
    }
    public int getId(){
        return id;
    }
}

还有一组其他 POJO 实体类,如 Movie、Actor、...

class Movie extends BaseEntity{
    private String name;
    private int year;
    private int durationMins;
    //getters and setters
}

我使用 BaseEntity 只是为了在某些界面中将其用作占位符。我永远不必存储 BaseEntity 对象。我必须只存储从 BaseEntity 扩展的实体对象。我应该如何注释这些类,以便从 BaseEntity 扩展的每个实体获得一个表。对于电影,它应该是(id、name、year、durationMins)。

【问题讨论】:

    标签: hibernate hibernate-annotations


    【解决方案1】:

    我在一篇完全不相关的帖子中找到了答案。我只需要将 BaseEntity 注释为@MappedSuperclass。下面的代码完成了我所需要的。

    @MappedSuperclass
    class BaseEntity {
        @Id
        private int id;
        //getters and setters.
    }
    @Entity
    class Movie extends BaseEntity {
        @Column
        private String name;
        @Column
        private int year;
        @Column
        private int durationMins;
        //getters and setters
    }
    

    【讨论】:

    • 很好,你只是比我快一点:) 当我认为 MappedSuperClass 容易得多时,很多这些问题都得到了推荐的“每个具体类的表”策略。
    【解决方案2】:

    您可以在BaseEntity 上使用@MappedSuperClass,并让Movie 对其进行扩展。

    @MappedSuperClass
    class BaseEntity {
        @Id
        private int id;
        ...
    }
    
    class Movie extends BaseEntity {
        ...
    }
    

    【讨论】:

      【解决方案3】:

      您需要的是 Table Per Concrete 类策略。在此策略中,您的 BaseEntity 不需要任何注释。更多解释请查看this

      【讨论】:

        猜你喜欢
        • 2016-02-14
        • 2015-12-15
        • 2017-01-24
        • 1970-01-01
        • 1970-01-01
        • 2011-12-05
        • 2010-10-21
        • 1970-01-01
        相关资源
        最近更新 更多