9

我有DisseminationArea以下Feature代码的子类:

@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;

   ...    
}

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

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

4

3 回答 3

19

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.

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:

@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.

于 2017-04-23T17:05:45.337 回答
0

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

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

于 2017-04-23T13:52:00.847 回答
0

或使用例如:

th:text="${OBJECTNAME.class.getSimpleName()}"

这很简单@DiscriminatorColumn...

于 2021-05-24T12:49:01.517 回答