Search code examples
jakarta-eejpa

Getting the Value of the Discriminator Column


I have a JPA Entity which uses a discriminator column. But I need to get access to the value of the discriminator as one of the fields of the entity. How do I that. If I create a method that matches the discriminator column I get the following error at deploy time:

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.example.PortEntity column: type (should be mapped with insert="false" update="false")

The entity definition:

@Entity(name="Port")
@DiscriminatorColumn(name="type",
         discriminatorType=DiscriminatorType.STRING,
         length=10)
@DiscriminatorValue(value="port")
@Table(name="vPorts")
@XmlRootElement(name="port")
public class PortEntity {

     ...

     @Column(name="type", length=20, insert=false, update="false")
     @XmlAttribute(name="type")
     public String getType() { ... }

     public void setType(String newType) {... }

     ...

     @Entity(name="SeaPort")
     @DiscriminatorValue(value="seaport")
     @XmlRootElement(name="seaport")
     public static class Sea
     extends PortEntity { ... }



     @Entity(name="AirPort")
     @DiscriminatorValue(value="seaport")
     @XmlRootElement(name="seaport")
     public static class Air
     extends PortEntity { ... }

}

Solution

  • If you want access value of @DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=10) you may just add method like:

    @Transient
    public String getDecriminatorValue() {
        return limitString(this.getClass().getName(), 10);
    }
    

    if you want access it in JQPL queries you need use TYPE operator: SELECT pe FROM PortEntity as pe WHERE TYPE(pe) = SomePortEntity