I have a Java Entity class and a Java Data Transfer Object, each of which has it's own layer of validation based on constraints.
I use Liquibase to generate changelogs (db schema) based on the state of the Java Entity classes.
But there is a bug in the liquibase-hibernate
integration dependency which is not mapping Bean Validation constraints such as @NotNull
or @Size
into the corresponding Liquibase changelogs:
https://github.com/liquibase/liquibase-hibernate/issues/149
https://github.com/liquibase/liquibase-hibernate/issues/301
This means the only way I can specify constraints for the database is inside the JPA @Column
annotation.
I wont be able to group the Bean Validation constraints used at the DTO layer into a composite annotation for use at the Java Entity layer, as it will simply be ignored anyway. Resulting in having to duplicate the constraint info into the @Column
annotation.
What is the best practice for sharing constraint metadata between the separate DTO and DB layers?
- A composite annotation containing all Bean Validation and JPA constraints? e.g
@Size
,@NotNull
,@Column
- Is there a library that facilitates sharing between the layers?
- Or is it expected that no Bean Validation constraints should be specified inside Java Entity and duplication cannot be avoided?
import jakarta.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
public class ItemOne {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@NotNull
private Long id;
@NotNull
@Size(max = 10)
@Column(name = "text", nullable = false, length = 100)
String text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
The associated DTO which has the Bean Validation constraints applied to fields:
import jakarta.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
public class ItemOneDTO {
@NotNull
private Long id;
@NotNull
@Size(max = 10)
String text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}