3

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<>();

    ....
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
Paweł Adamski
  • 3,285
  • 2
  • 28
  • 48
  • Check the spring validator: https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/validation.html – dbl Sep 04 '18 at 12:22
  • Another way of achieving it is to wrap the String itself. – dbl Sep 04 '18 at 12:23

3 Answers3

4

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.

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
1

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

Andre Albert
  • 1,386
  • 8
  • 17
  • Not sure if the thread below is valid but you should check it: https://stackoverflow.com/questions/2875149/what-does-the-length-attribute-do-when-set-on-the-column-jpa-annontation#answer-25803065 – dbl Sep 04 '18 at 12:31
0

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)

Sai prateek
  • 11,842
  • 9
  • 51
  • 66