views:

1856

answers:

3

Java has the transientkeyword. Why does JPA have @Transient instead of simply using the already existing java keyword?

+13  A: 

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.

Jawher
Yes, the semantics are different. But why was JPA designed this way?
Dilum Ranatunga
Not sure I'm understanding you, but have a look at "Pascal Thivent"'s answer ;)
Jawher
This is handy because you might not want to store the data in the database, but you do want to store it in the JPA Chaching system that uses serialization for store/restore of entities.
Kdeveloper
What "JPA Caching system" that uses serialisation for store/restore of entities ? a JPA implementation can cache an object in any way they wish, and serialisation doesn't enter into it.
DataNucleus
+5  A: 

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.

Pascal Thivent
+1  A: 

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 }

@Entity
public 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.

Esko
You should never mix field and property based annotations. It causes unspecified behavior. For the example to be valid, you should move the annotations on the id instance variable to the getId() method.
psp
@psp: Fair enough, edited as suggested.
Esko