I have an entity with a transient field. When I want to create a new instance of the object I lose my transient information. The following example demonstrates the issue. For the sake of the example let's say that barness is a transient field.
FooEntity fooEntity = new FooEntity();
fooEntity.setFoobosity(5);
fooEntity.setBarness(2);
fooEntity = fooEntityManager.merge(fooEntity);
System.out.println(fooEntity.getFoobosity()); //5
System.out.println(fooEntity.getBarness()); //0 (or whatever default barness is)
Is there any way to maintain my transient information?
Java's transient keyword is used to denote that a field is not to be serialized, whereas JPA's @Transient annotation is used to indicate that a field is not to be persisted in the database, i.e. their semantics are different.
@Transient annotation in JPA or Hibernate is used to indicate that a field is not to be persisted or ignore fields to save in the database. @Transient exist in javax. persistence package. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable class.
To ignore a field, annotate it with @Transient so it will not be mapped by hibernate.
What is @Transient annotation in Spring? @Transient annotation is used to mark a field to be transient for the mapping framework, which means the field marked with @Transient is ignored by mapping framework and the field not mapped to any database column (in RDBMS) or Document property (in NOSQL).
This is, more or less, working as designed. The semantics of transient are precisely that the data is not persisted. The entity returned from entityManager.merge(obj)
is, in fact, an entirely new entity that maintains the state of the object passed into merge (state, in this context, being anything that is not part of the persistent object). This is detailed in the JPA spec. Note: There may be JPA implementations that do maintain the transient field after the object is merged (simply because they return the same object), but this behavior is not guaranteed by the spec.
There are essentially two things you can do:
Decide to persist the transient field. It doesn't really seem to be transient if you need it after merging the class into the persistence context.
Maintain the value of the transient field outside of the persistent object. If this is what meets your needs, you may want to rethink the structure of your domain class; if this field is not part of the state of the domain object it really shouldn't be there.
One final thing: the main use case I've found for transient fields on domain classes is to demarcate derived fields, i.e., fields that can be recalculated based on the persistent fields of the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With