Is it safe to assume that @Transient makes JPA provider to leave annotated field always intact?

Viewed 634

Motivated by this answer I began to study more in details the functionality of JPA's @Transient annotation. In mentioned answer stands:

One merge or refresh too many and your transient field value is lost.

Then every documentation I have had a glance says approximately the same:

Fields annotated with @Transient are not persisted

I found nothing about ignoring such a field totally and I realize I have no explicit evidence but somehow I have always understood it implicitly like @Transient annotated fields are ignored by JPA (provider).

Would there be a point - for an example - to fetch such a field from the database if it is never persisted there, I mean persisted in a JPA context. For such there are @Column(insertable=false, updatable=false) I guess?

So could it really be that I should be aware that merge or refresh for an entity, managed or not at the time of operation, makes the value of some @Transient field change?

And if yes, what would be a simple example of such situation?

1 Answers
  • I would like to consider 3 scenarios

    • Calling merge on unmanaged entity where unmanaged entity is populated with a transient field
    • Calling merge on managed entity where managed entity is populated with a transient field after it became managed
    • Calling refresh on managed entity where managed entity is populated with a transient field after it became managed. It is not allowed to call refresh on a unmanaged entity anyway
  • Calling merge on unmanaged entity where unmanaged entity is populated with a transient field.

    • Implementation is free to return a new entity and that means transient field is lost. I have verified the behaviour with hibernate and it loses the value. Even if some implementations make it not lose value, I wouldn't rely it as merge is free to return new entity.
  • Calling merge on managed entity where managed entity is populated with a transient field after it became managed.

    • It is a managed entity so JPA need to provide repeatable read. So even if you perform merge, JPA has to satisfy both guarantees, i.e the object reference you have for the managed entity cannot change and that object should contain latest value from db. There is no reason for JPA to touch your transient field. It will just update any field that are managed and has been updated in the database since. I have verified this behaviour and behaves as expected.
  • Calling refresh on managed entity where managed entity is populated with a transient field after it became managed.

    • Same argument as merging managed entity. JPa cannot lose your transient value. I have verified this behaviour and behaves as expected.

Summary

  • You will lose the transient value of an unmanaged entity when you call merge.

GitRepo

Related