Video in progress
How does the @Transient annotation differ from Java's transient keyword?
@Transient makes only Hibernate ignore the field: it isn't written to the database, but it still takes part in Java serialization. The transient keyword excludes the field from Java serialization, and Hibernate doesn't persist it either.
📖 Answer
@Entity
public class Invoice {
@Id @GeneratedValue
private Long id;
private BigDecimal amount;
private BigDecimal taxRate;
@Transient
private BigDecimal total; // computed, no column
@PostLoad
void calc() {
total = amount.multiply(BigDecimal.ONE.add(taxRate));
}
}
When to use which:
- a computed value, a cache, a helper field for the UI:
@Transient; - something that must not be serialized (a logger or a connection, for example):
transient.
When Jackson converts to JSON, it looks at neither of them: a @Transient field shows up in the JSON (if there is a getter). To hide it from JSON you need @JsonIgnore.
One note: this is jakarta.persistence.Transient. Spring Data also has org.springframework.data.annotation.Transient; if you import that one in a JPA entity by mistake, Hibernate still treats the field as a column.
Sign up to mark studied questions and save your progress.