Kevin
Kevin

Reputation: 4128

Make a field transient for serialization, but non-transient for JPA

Question:
Is it possible to have a field persisted by JPA but skipped by serialization?

It is possible to achive the opposite (JPA skips a field and serialization doesn't), and if this feature is used, surely the reverse would be useful.

Something like this:

@Entity 
class MyClass {
    // Other fields.

    @NonTransient
    private transient String strangeField;
}

I am asking mostly out of curiosity, so I don't have a specific context.

Upvotes: 1

Views: 1803

Answers (2)

James
James

Reputation: 18389

You need to use property access, or use XML to map the entity instead of annotations.

Upvotes: 0

Kevin
Kevin

Reputation: 4128

One option is to use property access on the entity. Then, mark the field as transient. JPA will ignore the field and only use the getter. Thus, serialization skips the field, and JPA uses the getter.

@Entity(AccessType.Property)
class MyClass {
    // Other fields.

    private transient String strangeField;

    public String getStrangeField() {
        return strangeField;
    }

    public void setStrangeField(String strangeField) {
        this.strangeField = strangeField;
    }
}

Upvotes: 2

Related Questions