Jayram Kumar
Jayram Kumar

Reputation: 712

Java non-persistent but serializable variable

In java, how can I declare a variable which is not persistent to a database but it is serializable so that the variable is present in JSON representation of the object containing the variable?

I used the annotation @javax.persistence.Transient, but it doesn't work the way I want since @Transient variables are not serializable.

Upvotes: 1

Views: 579

Answers (1)

Assafs
Assafs

Reputation: 3275

The issue may be solved by a specific workaround using modifiers. In order to avoid persisting fields, you have 4 options: marking the field with the modifier static, final or transient; or adding the @Transient annotation. Each of these will prevent the field from being persisted into the DB (see here).

Not all these limitations also apply to serialization though. Static and transient modifiers will prevent serialization, but final modifier will not - it will not be persisted but will be serialized (Deserializing in this case is a bit longer, but possible).

I hope this will be applicable to your issue.

Upvotes: 1

Related Questions