Issue
Javax's @Transient
annotation when applied over an @Entity
class' field will prevent the annotated field from being persisted into the database as a column. Is there a method to selectively achieve this behavior (of excluding the persistence of a certain column) for a field in a MappedSuperclass?
To clarify, I want some field x
present in a MappedSuperclass to be persisted for some entity classes that extend the MappedSuperclass and excluded from persistence in some other extending entity classes.
I have tried shadowing the field x
in the extending class and annotating it with @Transient
, however, this doesn't seem to work. Is there any alternative approach that would enable this behavior?
Solution
Yes. In the children entity class that extends @MappedSuperclass
, you can configure it to use the property access for this transient field .
So assuming a given @MappedSuperclass
has a @Transient
field :
@MappedSuperclass
public abstract class Parent {
@Transient
protected LocalDateTime createdTs;
}
For the children entity that want to include this transient field , you could do :
@Entity
@Table(name = "foo")
public class Foo extends Parent {
@Id
private Long id;
@Access(AccessType.PROPERTY)
@Column(name= "createTs")
public LocalDateTime getCreatedTs() {
return this.createdTs;
}
}
And for the children entity that want to exclude this transient field , you could do :
@Entity
@Table(name = "foo")
public class Foo extends Parent {
@Id
private Long id;
}
Answered By - Ken Chan
Answer Checked By - Terry (JavaFixing Volunteer)