获得鉴别者专栏的价值

时间:2013-03-04 18:47:20

标签: java-ee jpa

我有一个使用鉴别器列的JPA实体。但我需要访问鉴别器的值作为实体的一个字段。我怎么样如果我创建一个与鉴别器列匹配的方法,我在部署时会收到以下错误:

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

实体定义:

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

}

2 个答案:

答案 0 :(得分:11)

@Transient
public String getDecriminatorValue() {
    return this.getClass().getAnnotation(DiscriminatorValue.class).value();
}

答案 1 :(得分:2)

如果您想要@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=10)的访问值,可以添加以下方法:

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

如果要在JQPL查询中访问它,则需要使用TYPE运算符: SELECT pe FROM PortEntity as pe WHERE TYPE(pe) = SomePortEntity