H​i​b​e​r​n​a​t​e​ ​d​i​s​c​r​i​m​i​n​a​t​o​r​-​v​a​l​u​e​用​法

墨蓝 2022-08-26 14:16 271阅读 0赞

#

这样就可以单独的用 CustomerA,CustomerB 这样的实例了, 做数据库修改时 就不用关心 flag 字段的值了,会自动的加 A 或 B 。 如果是使用 hibernate Annotation 而不是 xml 来描述映谢关系, 代码如下: @Entity @Table(name = “customer”) @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = “flag”, discriminatorType = DiscriminatorType.STRING) public class Customer{ } @Entity @DiscriminatorValue(value = “A”) public class CustomerA extends Customer{ } @Entity @DiscriminatorValue(value = “B”) public class CustomerB extends Customer{ } 这样就可以了。" class="reference-link">可能经常遇到这样的情况: 在数据库表中会有这样的一个字段用来区别记录的属性, 如: 在客户表中有 一个字段表示客户级别, 当这个记录为 A 时是一级客户, 为 B 时是二级客户。 在 用 hiberante 做 OR 表示时类可能是这样的: public class Customer{ private String flag; // 表示客户的级别 … } 然后,在程序中手动控制 flag 的值,但是这样当每个级的客户有不同的属 性时 Customer 类将包含所有级别的属性,这样不是很好。 hibernate 提供一个 Discriminator 映射的方法, 就是把一个表映射成不同 的类,有不同的属性。 public class Customer{ // 包含所有级别的公共属性 … } public class CustomerA extends Customer{ // 只包括一级客户的特有属性 } public class CustomerB extends Customer{ // 只包含二级客户特有的属性 } 这样更符合面向对象的原则,然后在 hbm.xml 中这样写: 这样就可以单独的用 CustomerA,CustomerB 这样的实例了, 做数据库修改时 就不用关心 flag 字段的值了,会自动的加 A 或 B 。 如果是使用 hibernate Annotation 而不是 xml 来描述映谢关系, 代码如下: @Entity @Table(name = “customer”) @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = “flag”, discriminatorType = DiscriminatorType.STRING) public class Customer{ } @Entity @DiscriminatorValue(value = “A”) public class CustomerA extends Customer{ } @Entity @DiscriminatorValue(value = “B”) public class CustomerB extends Customer{ } 这样就可以了。

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读