Hibernate Transient annotation

Hibernate @Transient annotation is used to indicate that a field is not to be persisted in the database.

For example- Let’s say you have created two variables in an entity class in one you want to save in database and second is derived from the first one. So we need not save the second field in the database and can be map with hibernate @Transient annotation.

What are persistent fields ?

  • Every non-static non-final entity field is persistent by default. (If we are not annotated any fields).

Non persistent or Transient fields :

  • Transient entity fields are fields that do not participate in persistence and their values are never stored in the database (similar to transient fields in Java that do not participate in serialization).
  • Static and final entity fields are always considered to be transient.
  • Other fields can be declared explicitly as transient using either the Java transient modifier or the JPA @Transient annotation (which only affects persistence):

static String transient1; // not persistent because of static
final String transient2 = “Satish”; // not persistent because of final
transient String transient3; // not persistent because of transient
@Transient String transient4; // not persistent because of @Transient

Let’s Look into an example :

Database table:

  • Sometimes it is required that define non persistent fields for representational purpose on view pages or to do some data manipulation purpose.
  • For the above table  User entity is created. User entity defined one non persistent field to convert sql.date to String.

  • In user entity dateOfBirthString field is non persistent variable. 
  • If we want to make dateOfBirthString field non persisatable and If we do not annotate with @Transient, dateOfBirthString field should be either static or final or transient, otherwise JPA identifies it as Unknown column.

Download Application – JPA-Transient.zip (11 KB)
Maven dependencies used all over JPA tutorials same. Please follow "Setting up Project" section to understand about project configuration.
persistence.xml and other code files reused from How to Persist an Entity in data base using JPA?
Each Sample application from download includes SQL file also.