热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何访问JPA中的鉴别器列-HowtoaccessdiscriminatorcolumninJPA

IhaveDisseminationAreaassubcalssforFeaturewiththefollowingcode:我使用以下代码将DisseminationArea作

I have DisseminationArea as subcalss for Feature with the following code:

我使用以下代码将DisseminationArea作为Feature的subcalss:

@Entity
@Table(name = "features")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "subtype_id", discriminatorType = DiscriminatorType.INTEGER)
public class Feature {

   @Id
   @Column(name="id")
   @GeneratedValue(generator="sqlite")
   @TableGenerator(name="sqlite", table="sqlite_sequence",
      pkColumnName="name", valueColumnName="seq",
      pkColumnValue="features")
   @Getter
   @Setter
   private long id;

   @ManyToOne
   @JoinColumn(name = "subtype_id")
   @Getter
   @Setter
   private FeatureSubtype featureSubtype;

   @ManyToOne
   @JoinColumn(name = "parent_id")
   @Getter
   @Setter
   private Feature parent;

   ...    
}

Unfortunately, this causes an exception when save this entity to database, because subtype_id field is used twice.

不幸的是,这会在将此实体保存到数据库时导致异常,因为subtype_id字段使用了两次。

Can I annotate it somehow so that JPA know it is the same field?

我可以以某种方式对其进行注释,以便JPA知道它是同一个字段吗?

2 个解决方案

#1


2  

If a discriminator column makes sense with InheritanceType.JOINED is worth discussing. I would tend to omit it on joined strategy and only use it with InheritanceType.SINGLE_TABLE.

如果一个鉴别器列对于InheritanceType有意义.JOINED值得讨论。我倾向于在加入策略中省略它,并且只将它与InheritanceType.SINGLE_TABLE一起使用。

Nevertheless, it's possible to map it without duplicate column errors.

不过,可以映射它而不会出现重复的列错误。

If your superclass entity has an inheritance / discriminator definition like:

如果您的超类实体具有继承/鉴别器定义,例如:

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "subtype_id", discriminatorType = DiscriminatorType.INTEGER)

You just have to adjust the mapping to not update the value as usual by setting it readonly:

您只需通过将其设置为readonly来调整映射以不像往常一样更新值:

@Column(name="subtype_id", insertable = false, updatable = false)
protected int subTypeId;

public int getSubTypeId() {
    return subTypeId;
}

Now you can access the discriminator value of the entity.

现在您可以访问实体的鉴别器值。

#2


0  

Same column name is used for relation FK to FeatureSubtype. Use other name for discriminator or don't use discriminator at all.

相同的列名用于FK与FeatureSubtype的关系。使用其他名称作为鉴别器或根本不使用鉴别​​器。

In Hibernate, discriminator column on joined inheritance is supported but not required. Hibernate is querying all subtables to determine correct subclass.

在Hibernate中,支持连接继承的discriminator列,但不是必需的。 Hibernate正在查询所有子表以确定正确的子类。


推荐阅读
author-avatar
晨风流云
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有