Hibernate注解@Inheritance、@DiscriminatorColumn、@DiscriminatorValue用途

这三个注解用于hibernate多表同时保存使用,多表分为主子表形式

  • Inheritance
    必须定义其属性strategy

    • strategy=InheritanceType.SINGLE_TABLE 将父类和所有子类集合,存在一张表中,全部创建新的字段
    • strategy=InheritanceType.TABLE_PER_CLASS 每一个类创建一个表,这些表相互独立
    • strategy=InheritanceType.JOINED 将父类、子类分别存放在不同的表中,并且建立相应的外键,以确定相互之间的关系
  • DiscriminatorColumn
    只能用在@Inheritance( strategy=InheritanceType.SINGLE_TABLE或JOINED下)
    都有默认值,所以属性均可选,源码及解释如下:

/**
 * <pre>
 *     Example:
 *     &#064;Entity
 *     &#064;Table(name="CUST")
 *     &#064;Inheritance(strategy=SINGLE_TABLE)
 *     &#064;DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)
 *     public class Customer { ... }
 *     &#064;Entity
 *     public class ValuedCustomer extends Customer { ... }
 * </pre>
 */
public @interface DiscriminatorColumn {

    /**
     * (Optional) The name of column to be used for the discriminator.
     * 对应列名
     */
    String name() default "DTYPE";

    /**
     * (Optional) The type of object/column to use as a class discriminator.
     * Defaults to {@link DiscriminatorType#STRING DiscriminatorType.STRING}.
     * 对应列的字段类型,DiscriminatorType有STRING、CHAR、INTEGER
     */
    DiscriminatorType discriminatorType() default STRING;

    /**
     * (Optional) The SQL fragment that is used when generating the DDL
     * for the discriminator column.
     * <p> Defaults to the provider-generated SQL to create a column
     * of the specified discriminator type.
     * DDL生成时使用的SQL片段,默认为提供程序生成的SQL来创建列
     */
    String columnDefinition() default "";

    /**
     * (Optional) The column length for String-based discriminator types.
     * Ignored for other discriminator types.
     * 字符串类型要求的长度,其他类型此项请忽略
     */
    int length() default 31;
}
  • DiscriminatorValue
    插入的值,直接使用即可

用途:hibernate映射时,采用主从表关联形式映射,父类代表主表,子类注解代表将向主表插入数据库的数据值

  • 父类
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name=“a_type”, discriminatorType=DiscriminatorType.STRING, length=30)
  • 子类
    @DiscriminatorValue(“我是值”)
    表中有一列a_type,类型为字符串,长度30,操作插入的值为“我是值”
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值