In this quick article, we will understand the usage of JPA @Transient annotation in the Spring boot application.
@Transient - JPA annotation specifies that the property or field is not persistent. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable class.
@Transient - JPA annotation Example 1
The @Transient annotation is used to specify that a given entity attribute should not be persisted.
Sometimes, we may want to make a field non-persistent. We can use the @Transient annotation to do so. It specifies that the field will not be persisted.
So let's annotate the field age with the @Transient annotation:
@Entity
@Table(name="STUDENT")
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name="STUDENT_NAME", length=50, nullable=false)
private String name;
@Transient
private Integer age;
// other fields, getters and setters
}
As a result, the field age will not be persisted to the table.
@Transient - JPA annotation Example 2
In the below example, we are not persisting currentUser instance in the Employee entity:
Employee.java
@Entity
public class Employee {
@Id
private int id;
@Transient
private User currentUser;
...
}
User.java
@Entity
public class User {
@Id
private int id;
}
Comments
Post a Comment