Gallop
Gallop

Reputation: 23

Play!Framework 2 Java model string field length annotations

To achieve best performance and validation convenience, which of these annotations are needed for a String field?

database: MySQL

A field to store district name

@Column(length=50)  // javax.persistence.Column

Is this going to be converted to varchar(50)? Or I need this one specifically:

@Column(columnDefinition='varchar(50)') 

And another two annotations

@MaxLength(50) // play.data.validation.Constraints.MaxLength
@Length(max=50) // com.avaje.ebean.validation.Length, is this one useful or not required anyway?
public String districtName;

I think I need @Column(length=50) for definition and @MaxLength(50) for validation at same time? Or one of these two will imply the other one automatically?

Thanks.

Upvotes: 2

Views: 4144

Answers (1)

Wayan Wiprayoga
Wayan Wiprayoga

Reputation: 4562

As far as I know, when we mark String variable with these annotation:

  1. @javax.persistence.Column(length=50)
  2. @javax.persistence.Column(columnDefinition='varchar(50)'). Note: I am use postgreSQL, and this will create column definition with character varying data type
  3. @com.avaje.ebean.validation.Length(50)

the three annotations above has the same purpose. Those will create column definition with character varying data type and length of 50 characters on database.

Without the @Constraint.MaxLength(50), you will get exception like below when you entered input value whose length greater than 50:

Execution Exception [ValidationException: validation failed for: models.TheModel]

I think, there should be a way to handle above exception, but honestly I don't know how to do that until now.


Advice

My advice for you is to choose one out of the 3 annotations above (It is your preference) with the use of anotation @Constraint.MaxLength(50). For me, it is the easiest and the simplest way, and you can easily make the form using play framework scala-template-helper.

Upvotes: 6

Related Questions