Tala
Tala

Reputation: 927

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

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;
    }

Upvotes: 1

Views: 320

Answers (1)

SternK
SternK

Reputation: 13071

You should not use @Transient annotation on these methods:

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

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.

Upvotes: 1

Related Questions