Explain Codes LogoExplain Codes Logo

What is the easiest way to ignore a JPA field during persistence?

java
jpa
serialization
persistence
Anton ShumikhinbyAnton Shumikhin·Nov 12, 2024
TLDR

The easiest way to exclude a field from JPA persistence:

@Transient private String implementationDetail;

This makes implementationDetail a purely in-memory field — invisible to JPA. It's like your field joined a Witness Protection Program!

JSON Serialization and Deserialization

Sometimes your persistence needs differ from your serialization needs. Here, @Transient joins forces with @JsonInclude. It's like Batman and Robin fighting crime, but here they fight unwanted persistence and serialization:

@Transient @JsonInclude(JsonInclude.Include.NON_NULL) private String myField;

With this setup, myField will not be persisted, nor will it be serialized to JSON if its value is null.

Implications for Equality and Fetching

Careful! Using @Transient can affect equals and hashCode methods if the field plays a part in comparisons between entity instances. It's like being a detective and some clues are just not there.

When it comes to fetching data, remember @Transient makes the field invisible to JPA. So don't try to reference it in your JPQL queries unless you are a fan of getting errors.

More Control of Your Fields

For fine-tuned control over your fields, JPA enables you to specify your field access strategies. It's like setting rules for your fields to follow:

@Access(AccessType.PROPERTY) @Transient private String someField;

The above code gives someField a disguise plus a strict rule to follow — it won't be persisted, and JPA will access it via getters and setters and not directly.

Alternatives & Additional Settings

Read-Only Relationships

To make a read-only relationship, use @JoinFormula. It's like having a spy who only observes and never acts:

@ManyToOne @JoinFormula("(SELECT ...)") private SomeEntity readOnlyEntity;

Leveraging existing Identifiers

Reuse an existing primary key from another table with @MapsId. It's like visiting your neighbour just to use their wi-fi:

@MapsId @OneToOne private RelatedEntity alreadyExistingPK;

Hibernate-specific field exclusion

To keep Hibernate from persisting specific inner fields, play detective and use insertable = false and updatable = false. It's like telling Hibernate, "These are not the fields you're looking for!":

@ManyToOne @JoinColumn(name = "some_id", insertable = false, updatable = false) private SomeOtherEntity someInnerNonPersistentField;