Why does JPA have a @Transient annotation?
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.
Because they have different meanings. The @Transient
annotation tells the JPA provider to not persist any (non-transient
) attribute. The other tells the serialization framework to not serialize an attribute. You might want to have a @Transient
property and still serialize it.
As others have said, @Transient
is used to mark fields which shouldn't be persisted. Consider this short example:
public enum Gender { MALE, FEMALE, UNKNOWN }@Entitypublic Person { private Gender g; private long id; @Id @GeneratedValue(strategy=GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } public Gender getGender() { return g; } public void setGender(Gender g) { this.g = g; } @Transient public boolean isMale() { return Gender.MALE.equals(g); } @Transient public boolean isFemale() { return Gender.FEMALE.equals(g); }}
When this class is fed to the JPA, it persists the gender
and id
but doesn't try to persist the helper boolean methods - without @Transient
the underlying system would complain that the Entity class Person
is missing setMale()
and setFemale()
methods and thus wouldn't persist Person
at all.