☰ See All Chapters |
JPA @Transient Annotation
JPA Transient annotation is used to mark the fields which shouldn't be persisted. Number of variables of entity class should be same as the number of columns of the corresponding database table. If it is not same then entity class cannot be persisted. Hence the variables which are not mapped to columns of database table can be annotated with Transient annotation. Now let see an example for @Transient annotation.
JPA @Transient Annotation Example
Student.java
package com.java4coding;
import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient;
@Entity @Table(name = "STUDENT") public class Student {
@Id private int id;
private String firstName;
private String lastName;
private int marks;
@Transient private String fullName;
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getMarks() { return marks; } public void setMarks(int marks) { this.marks = marks; } public String getFullName() { setFullName(createFullName()); return fullName; } public void setFullName(String fullName) { this.fullName = fullName; }
public String createFullName() { String fullName = firstName.substring(0, 1).toUpperCase() + firstName.substring(1) + " " + lastName.substring(0, 1).toUpperCase() + lastName.substring(1); return fullName; } } |
Database Script
CREATE TABLE STUDENT ( ID INT NOT NULL, FIRSTNAME VARCHAR(20) DEFAULT NULL, LASTNAME VARCHAR(20) DEFAULT NULL, MARKS INT DEFAULT NULL, PRIMARY KEY (ID) ); |
When the variable fullName is not annotated with @Transient we will get the exception as below:
All Chapters