nagy.zsolt.hun
nagy.zsolt.hun

Reputation: 6694

Java JPA - constraint on Map size

Can I have constraints on the size of a map in an entity? I want to make sure it contains at least one non-null value.

@Entity
public class Product {

    @Id
    @GeneratedValue
    private UUID id;

    // TODO names should contain at least one non-null value
    @ElementCollection
    @MapKeyColumn(name="lan", length=2)
    @Column(name="name")
    Map<String,String> names;

    protected Product() {}
    public Product(Map<String, String> names) {
        this.names = names;
    }

}

Upvotes: 0

Views: 1325

Answers (1)

SplinterReality
SplinterReality

Reputation: 3410

For cases like this, I would tend to recommend Hibernate Validator. It's run automatically by most JPA providers, and the annotations provide a concise way to validate both simple cases like this, and implement more complex logic.

    @Entity
public class Product {

    @Id
    @GeneratedValue
    private UUID id;

    // TODO names should contain at least one non-null value
    @ElementCollection
    @MapKeyColumn(name="lan", length=2)
    @Column(name="name")
    @Size(min=1)   // <- This is all that's needed to implement what you're asking
    @NotEmpty  // Also implies not-null - for >= 1, this line alone is sufficient
    Map<String,String> names;

    protected Product() {}
    public Product(Map<String, String> names) {
        this.names = names;
    }

}

Upvotes: 3

Related Questions