Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a feeling that adding fields marked with @Transient annotation to entity is very bug-prone. Am I right?

I have some philosophical intuitive feeling that adding fields which doesn't mapped to the DB corrupts entity classes and is a wrong way of solving problems.

But are there any concrete situations where using @Transient fields leads to implicit and hard fixing problems?

For example, is it possible that adding or removing 2nd level cache will break our app when there are @Transient fields in our entities?

Considerable update: after some thinking on @Transient fields it seems to me that @Transient fields just should be used in a proper way.

By 'proper way' I mean that entity always should have same behavior. It means that it's a very error-prone behavior when getters returns null's from time to time depending on @Transient field value. And it means that @Transient fields should always be initialized.

And I see only 2 cases of proper usage:

  1. @Transient fields should be initialized in object's constructor:

    @Entity
    public class SomeEntity
       @Id
       private long id;
    
       @Transient
       private String transientField;
    
       public SomeEntity () {
          transientField = "some string";
       }       
       ...
    }
    
  2. @Transient fields can be lazy 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 anyone coment these 2 cases or describe other cases which I missed?

like image 320
Roman Avatar asked Nov 15 '22 10:11

Roman


1 Answers

I am using the Transient annotation in some projects that persist with hibernate as well and didn't have any problems yet.

It is usually used for fields that can be determined by other persistent properties and using a cache should work also, because Javas Serialization mechanisms (caches usually expect the cached objects to be serializable) take the Transient annotation into consideration, too. I think it is preferrable to use transient getter and setter properties that provide the information instead of instance fields whenever possible.

like image 107
Daff Avatar answered Dec 24 '22 05:12

Daff