Hibernate – @Transient Annotation with Example
Last Updated :
07 Jun, 2023
@Transient annotation in Hibernate is used to mark a property or field in an entity class as transient. This means that the field or property marked as transient should be excluded when the data persists in the database. Wherever an entity is mapped to a database table, by default all the non-transient fields and properties are persisted. There are certain fields or properties in an entity that should be ignored during the data persistence process such as the data which is being calculated for displaying, temporary variables, and other data which is relevant only within the application logic but is not required in the database. By using the @Transient annotation to that field or a property Hibernate can exclude that field from the persistence process and the corresponding column will not be created in the database table.
Example of @Transient Annotation
Example 1:
Java
@Entity
public class MathsOperation {
@Id
@GeneratedValue
private Long operationID;
private String operation;
private int num1;
private int num2;
@Transient
private int getAnswer()
{
if (operation == "add" ) {
return num1 + num2;
}
else if (operation == "subtract" ) {
return num1 - num2;
}
else if (operation == "multiply" ) {
return num1 * num2;
}
else if (operation == "division" ) {
return num1 / num2;
}
}
}
|
Example Explanation: In the above example, the MathsOperation entity class has a field for operationID, operation name, num1, and num2. After that, we created a method as getAnswer and marked it as @Transient to specify that it should not be considered for persistence. The method calculates the answer for num1 and num2 based on the operation which is specified, but the answer which will be generated will not be stored in the database. By using @Transient we can exclude the specific field or method from being persisted in our database. In this case, we are adding a @Transient annotation for our getAnswer method to indicate that the method is not a part of the persistent state of the MathsOperation entity.
Example 2:
Java
@Entity
public class ProductInfo {
@Id
@GeneratedValue
private Long productID;
private String productName;
private int productPrice;
@Transient
private int discountPrice = productPrice * 5 / 100 ;
}
|
Example Explanation: In the above example, we are creating a Product Info entity class which has a field for productID, product name, product price a,d a discounted price. We are marking the discounted price property as @Transient because we have to exclude the value of this variable from persisting in the database. We are calculating the value for a discounted price from the product price by using a specific multiplication factor. Marking it with @Transient annotation will exclude this variable from adding it to our database operations.
Share your thoughts in the comments
Please Login to comment...