简体   繁体   English

继承 class 上的 JPA/Hibernate 关系返回 null

[英]JPA/Hibernate relationship on inherited class return null

I have a hierarchical class system for entities and they are all fine, until I introduce relationships.我有一个用于实体的分层 class 系统,它们都很好,直到我引入关系。 Here are some example code:下面是一些示例代码:

BaseClass :基类

@MappedSuperclass
public class BaseClass
{

    // Some fields
    // Ids are MySQL autoincrementing unsigned BIGINT
    protected Long id;
    // ... other fields

    @JsonCreator
    public BaseClass (
        // ...fields
    )
    {

        // assign fields
    }

    public BaseClass () { /** Default copy constructor */ }

    public BaseClass update (BaseClass value)
    {
        // repeat bellow line for all fields
        this.field1 = (value.field1 != null) ? value.field1 : this.field1;
        // finally, for chaining
        return this;
    }

    // Getters and Setters for all fields

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false)
    @JsonProperty("id")
    public Long getId ()
    {
        return this.id;
    }

    public BaseClass setId (Long value)
    {
        this.id = value != null ? value : this.id;
        return this;
    }

    @Column(name = "field1")
    @JsonProperty("field1")
    public String getField1 ()
    {
        return this.field1;
    }

    public BaseClass setField1 (Field1Type value)
    {
        this.field1 = value;
        return this;
    }

}

InheritedClass :继承类

@Entity
@Table(name = "`table_name`")
@DynamicInsert
@DynamicUpdate
public class InheritedClass extends BaseClass implements Serializable
{
    /**
     * the value is for demonstration only, it's randomly generated per serializable entity
     */
    private static final long serialVersionUID = 1L;

    private List<RelatedClass1> relatedClass1Field;
    private RelatedClass2 relatedClass2Field;

    public InheritedClass () { /** Default copy constructor */ }

    public InheritedClass (BaseClass value)
    {
        super.update(value);
    }

    // inheritedClassField is the field in the many-to-one end of the relationship in RelatedClass1
    @Transient // javax.persistence, not bean
    @JsonProperty("related_class1_field")
    @OneToMany(
        targetEntity=RelatedClass1.class
        , fetch=FetchType.EAGER
        , cascade = { CascadeType.ALL }
        , mappedBy = "inheritedClassField"
    )
    public List<RelatedClass1> getRelatedClass1Field ()
    {
        return this.relatedClass1Field;
    }

    public InheritedClass setRelatedClass1Field (List<RelatedClass1> value)
    {
        this.relatedClass1Field = value;
        return this;
    }

    // inheritedClassField is the field in the many-to-one end of the relationship in RelatedClass1
    @Transient // javax.persistence, not bean
    @JsonProperty("related_class2_field")
    @ManyToOne(
        targetEntity=RelatedClass2.class
        , fetch=FetchType.EAGER
        , cascade = { CascadeType.ALL }
    )
    @JoinColumn(
        name = "related_id"
        , referencedColumnName = "id"
    )
    public RelatedClass2 getRelatedClass2Field ()
    {
        return this.relatedClass2Field;
    }

    public InheritedClass setRelatedClass2Field (RelatedClass2 value)
    {
        this.relatedClass2Field = value;
        return this;
    }

}

When I try to access an instance of InheritedClass , the relatedClass1Field and relatedClass2Field are null , however they are filled in database.当我尝试访问InheritedClass的实例时, relatedClass1FieldrelatedClass2Fieldnull ,但是它们已填充到数据库中。

BUT

If I define the relationship through field access strategy, they return the correct value:如果我通过字段访问策略定义关系,它们会返回正确的值:

    @Access(AccessType.FIELD)
    @OneToMany(
        targetEntity=RelatedClass1.class
        , fetch=FetchType.EAGER
        , cascade = { CascadeType.ALL }
        , mappedBy = "inheritedClassField"
    )
    private List<RelatedClass1> relatedClass1Field;

    @ManyToOne(
        targetEntity=RelatedClass2.class
        , fetch=FetchType.EAGER
        , cascade = { CascadeType.ALL }
    )
    @JoinColumn(
        name = "related_id"
        , referencedColumnName = "id"
    )
    private RelatedClass2 relatedClass2Field;

    
    @JsonProperty("related_class1_field")
    public List<RelatedClass1> getRelatedClass1Field ()
    {
        return this.relatedClass1Field;
    }

    public InheritedClass setRelatedClass1Field (List<RelatedClass1> value)
    {
        this.relatedClass1Field = value;
        return this;
    }


    @JsonProperty("related_class2_field")
    public RelatedClass2 getRelatedClass2Field ()
    {
        return this.relatedClass2Field;
    }

    public InheritedClass setRelatedClass2Field (RelatedClass2 value)
    {
        this.relatedClass2Field = value;
        return this;
    }

You should not use @Transient annotation on these methods:您不应该在这些方法上使用@Transient注释:

@Transient
@OneToMany(
   targetEntity=RelatedClass1.class
   , fetch=FetchType.EAGER
   , cascade = { CascadeType.ALL }
   , mappedBy = "inheritedClassField"
)
public List<RelatedClass1> getRelatedClass1Field ()
// ...

@Transient
@ManyToOne(
   targetEntity=RelatedClass2.class
   , fetch=FetchType.EAGER
   , cascade = { CascadeType.ALL }
)
@JoinColumn(
   name = "related_id"
   , referencedColumnName = "id"
)
public RelatedClass2 getRelatedClass2Field ()
// ...

According to the documentation @Transient annotation specifies that the property or field is not persistent.根据文档@Transient注释指定属性或字段不是持久的。

And simple example.和简单的例子。 Imagine you have the following entity:假设您有以下实体:

@Entity
@Table(name = "TST_PATIENT")
public class Person {

    private Long id;
    // ...
    private Date dateOfBirth;

    @Id
    @Column(name = "P_ID")
    public Long getId() {
       return id;
    }
    
    @Column(name = "P_DOB")
    public Date getDateOfBirth() {
       return dateOfBirth;
    }
    
    @Transient
    public long getAge() {
       return ChronoUnit.YEARS.between(
          LocalDateTime.ofInstant( Instant.ofEpochMilli( dateOfBirth.getTime()), ZoneOffset.UTC),
          LocalDateTime.now()
       );
    }

    // setters omitted for brevity
}

Here we use @Transient annotation because actually we do not have age column in the TST_PATIENT table (it's just calculated based on the other persisted field) and we want to instruct hibernate exclude this property from being a part of the entity persistent state.这里我们使用@Transient注释,因为实际上我们在TST_PATIENT表中没有age列(它只是根据另一个持久化字段计算得出)并且我们要指示 hibernate 将此属性排除在实体持久性 state 的一部分之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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