I feel that adding fields marked with @Transient annotation to the entity is very error prone. I'm right?

I have some kind of intuitive philosophical feeling that adding fields that are not tied to the database corrupts entity classes and is the wrong way to solve problems.

But are there any specific situations where the use of fields @Transientleads to implicit and hard fix problems?

For example, is it possible that adding or removing a second level cache will ruin our application if there are fields in our objects @Transient?

Significant update : after some reflection on the fields, @Transientit seems to me that the fields @Transientshould be used properly.

By “right image” I mean that an entity must always have the same behavior. This means that this is a very error prone behavior when getters returns nullfrom time to time depending on the value of the @Transient field. And that means the @Transient fields should always be initialized.

And I see only 2 cases of proper use:

  • The @Transient fields must be initialized in the object constructor:

    @Entity
    public class SomeEntity
       @Id
       private long id;
    
       @Transient
       private String transientField;
    
       public SomeEntity () {
          transientField = "some string";
       }       
       ...
    }
    
  • @Transient fields can be lazily initialized:

    @Entity
    public class SomeEntity
       @Id
       private long id;
    
       @Transient
       private String transientField;
    
       public String getTransientField () {
          synchronized (lock) {
             if (transientField == null) {
                transientField = "some string";
             }   
          }
          return transientField;
       }       
       ...
    }
    

Can someone fulfill these two cases or describe other cases that I missed?

+5
source share
1 answer

Transient , , .

, , , Serialization Javas ( , ) Transient. , getter setter, .

+1

All Articles