Paweł Adamski
Paweł Adamski

Reputation: 3415

How to add constraint to collection items

I have an entity with collection of strings. I would like to add a constrains that will check if all items in the collection have size less then 255.

Let's say I have an entity Area with a collection of references. I would like to be sure that all references are shorter then 255 characters. Do you know how can I achieve it.

@Entity
@Table(name = "AREA")
public class Area  Serializable {

    private static final long serialVersionUID = -4756123949793458708L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private Integer id;

    @ElementCollection
    @CollectionTable(name = "AREA_REFERENCES", joinColumns = @JoinColumn(name = "AREA_ID"))
    @Column(name = "REFERENCE", nullable = false)
    @Size(max = 255) // THIS ANNOTATION SEEMS TO NOT WORK
    private Set<String> references = new HashSet<>();

    ....

Upvotes: 3

Views: 393

Answers (3)

Thomas Fritsch
Thomas Fritsch

Reputation: 10147

Annotating like this

@Size(max = 255)
private Set<String> references;

means the Set<String> is allowed to contain a maximum of 255 strings. Of course this is not what you want.

Instead, you want each string to have a maximum of 255 characters: You can achieve it by annotating the type parameter within < > like this:

private Set<@Size(max = 255) String> references;

For that you will need quite new versions of Hibernate Validator (6.0.x) and Bean Validation (2.0.1).

See also this answer for a similar problem.

Upvotes: 4

Sai prateek
Sai prateek

Reputation: 11926

For validation, you could add a like @Size(max=allowed_length) constraint from the Bean Validation API (JSR 303).

Hibernate uses Bean Validation constraints to generate an accurate database schema. for example :

@Size.max leads to a varchar(max) definition for Strings and @Min, @Max lead to column checks (like value <= max)

Upvotes: 0

Andre Albert
Andre Albert

Reputation: 1394

According to how-to-limit-the-column-length-while-using-collection-of-primitive-type you could set the size constraint to the Column annotation.

Upvotes: 1

Related Questions