简体   繁体   中英

How to access discriminator column in JPA

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

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

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

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.

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

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

Or use for example:

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

This is far simple the using @DiscriminatorColumn...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM