Do I have to use Serializable for JPA and Hibernate entities?


#1

Reading through Serialization chapter from Effective Java, I realized I still have some Serializables here and there in my codebase (Spring Boot web app -> Spring Data -> Hibernate). The recommendation is to avoid serialization as much as one can.

Do I still need to implement Serializable?
What are the reasons for doing so in Hibernate?
If I do so, how can it be exploited?

example:

@MappedSuperclass
@Getter
public class AbstractEntityWithVersion<ID extends Serializable> implements Identifiable<ID> {

    @Id
    private final ID id;

    @Version
    @Column(name = "REC_VERSION", nullable = false)
    private Long version;

    protected AbstractEntityWithVersion() {
        this.id = null;
    }
}
public interface Identifiable<ID extends Serializable> {
	ID getId();
}

Why does ID in this example have to be Serializable?


#2

Entities do not need to be Serializable. However, if you want to serialize them, you can safely implement Serializable.

The identifier has to be Serializable because that’s a JPA requirement since the identifier might be use as the key for a second-level cache entry.