【问题标题】:Hibernate - adding two class in one tableHibernate - 在一张表中添加两个类
【发布时间】:2017-04-12 11:42:47
【问题描述】:

如何使用 Hibernate 在一张表中添加基于类和后代类?

基础类

 public class Id{

 protected int id
 }

后代类

 public classs User exetends Id{
 public String username;
 public String password;
 }

在一个表 USERS 中具有以下属性:id、用户名、密码。

【问题讨论】:

标签: java mysql hibernate


【解决方案1】:

据我了解。

您想拥有一个Base 实体。并且 Base 实体应该由其他 Descendant 实体扩展。换句话说,Descendant 应该具有来自 Base 实体的所有属性。此设计的一个用例是为 Base 实体类中的所有 Descendant 类提供通用属性(id、createdDate、updatedDate)。

一种方法是:

BaseEntity(基类)

@MappedSuperclass
public class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    //..setter and getters
}

用户(后代类)

@Entity
@Table(name = "user")
public class User extends BaseEntity {

    @Column(name = "name")
    private String name; //User specific properties

    //..setters and getters here
}

【讨论】:

    【解决方案2】:

    首先你需要用@Entity标记它们以表明它们是表,然后在顶层设置表名@Table。要使用继承,您需要选择一个策略:对于这个实例,您需要 SINGLE_TABLE。然后为了选择正确的类型,需要@DiscriminatorColumn,设置列名和鉴别器类型——在这种情况下,我选择了INTEGER。您还需要在类型注释中添加 updatable = false 和 insertable = false 以便它们不能被修改。

    @Entity
    @Table(name = "TABLE_NAME")
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name = "TYPE",discriminatorType = DiscriminatorType.INTEGER)
    public class Id {
    
        @Column(name="TYPE", insertable=false, updatable=false)
        private Integer type;
    
    }
    

    在您的子类上,您需要用@Entity@DiscriminatorValue 标记它们(在本例中为1)。

    @Entity
    @DiscriminatorValue(value = "1")
    public classs User exetends Id{
    
        public String username;
        public String password;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 2018-07-26
      • 1970-01-01
      • 2021-01-06
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多