Empty constructors and setters on JPA Entites

entity, invariants, jpa

Solution

With JPA, the default constructor is required, however, you are not required to use setters. You can choose a property access strategy(field or method) based on where you place the annotations.

The following code will use direct field access and will work as a part of an entity without a setter:

@Column(name = DESCRIPTION)
private String description;

public String getDescription() { return description; }

Versus method access with a setter:

private String description;

@Column(name = DESCRIPTION)
public void setDescription(String description) {
     this.description = description;
}

public String getDescription() { return description; }

Problem

I don't like the requirement on have at least one empty constructor and public setters on JPA entities. While I understand the issue on the EntityManager side, this invalidates class invariants. Does anyone have a solution for this (design pattern or idiom level) ? Thanks! Igor

Original source