What is the difference between using @Transient and Transient in an attribute of a JPA entity?

Asked

Viewed 437 times

16

Studying some third-party codes, I came across different ways to define that a particular attribute of an Entity will not be related to a column in the database.

Among the shapes I found, the first uses the annotation @Transient just above the property declaration line (Example 1) and the second is incorporated transient in the property declaration line itself (Example 2).

Example 1:

@Transient
private int idValidacao;

Example 2:

private transient int idValidacao;

What is the difference between these two ways of declaring an attribute as transient and its advantages and disadvantages between?

2 answers

19


@Transient is a JPA annotation and is directly related to data persistence. Fields marked with this annotation will not be considered in framework generated Inserts, updates... .

transient is a java modifier, which should be used to mark fields that should not be considered in the serialization process, when serializing class data to a file, or to network for example.

They have different purposes, and their use is also different.

2

The annotation @Transient can be used in the attribute of a class, or in a method get, in your case getIdValidacao(). The way it is established is related to a class annotation, being @Access(AccessType.FIELD) to be in an attribute, or @Access(AccessType.PROPERTY) for method.

Unlike this, but serving the same purpose, there is one of the reserved words of the Java language, the transient, and it has no relation to the JPA specification, but to the interface java.io.Serializable.

When a class is flagged with this interface, something mystical happens, methods not shown in the interface signature, writeObject(ObjectOutputStream) and readObject(ObjectInputStream), appear without your consent to a possible serialization, but what is this?

Although using JPA in your project, use transient can help you relieve the storage of objects in memory while running @Stateful Enterprise Java Beans (EJB), or even Contexts and Dependency Injection (CDI) scopes other than @RequestScoped, because the purpose of serialization itself is to store files in memory, even if they are not being used, as in this scenario, or for a possible record in files.

It is important to inform a serialVersionUID so that the objects in memory, the Pojos, do not get confused on their own, and when saving them in file, it is recommended to use a Serialization Proxy, mentioned by Joshua Bloch in the book Effective Java.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.