获取鉴别器列的值

问题描述 投票:0回答:3

我有一个使用鉴别器列的 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 { ... }

}
jakarta-ee jpa
3个回答
23
投票
@Transient
public String getDecriminatorValue() {
    return this.getClass().getAnnotation(DiscriminatorValue.class).value();
}

4
投票

如果您想要访问

@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


0
投票

反射在性能方面不太好...如果你使用JPA,让我们用原生查询来检索。

  @Query(value = "select type from Port p where p.id = :id", nativeQuery = true)
    Optional<String> findIssueTypeById(@Param("id") Long id);
© www.soinside.com 2019 - 2024. All rights reserved.