Empty constructors and setters on JPA Entites

Igor Couto picture Igor Couto · Jun 22, 2009 · Viewed 17.3k times · Source

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

Answer

Brad C picture Brad C · Jun 23, 2009

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; }