13

When I define a variable in Model class as a String, it is converted as 'VARCHAR(255)' in DB.

However, I want to save more than 255 because this data is very long text consisting of several paragraphs.

As far as I remember, there is a TEXT type in DB to save very long text.

How can I define TEXT type in Play! framework?

I tried Constraints.MaxLength and Constraints.Max defined in Play! framework api.

However, still 1.sql file (created by Ebean DDL automatically) defines this variable as VARCHAR(255).

Thanks, in advance!

DataNucleus
  • 15,199
  • 3
  • 30
  • 37
byron1st
  • 793
  • 1
  • 8
  • 29

2 Answers2

22

In your model, just use the column definition set as TEXT:

@Entity
public class MyEntity extends Model {

    @Id
    private Long id;

    @Column(columnDefinition = "TEXT")
    private String aLongText;
    ....

}

I already used it with Postgres, don't know if it is ok with other database server.

ndeverge
  • 20,808
  • 4
  • 54
  • 84
9

You could use the @Lob annotation on your field which will yield type longtext on MySQL and type text on PostgreSQL:

package models;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;

@Entity
public class Foo {

    @Id
    public Long id;

    @Lob
    public String bar;

}

in MySQL this yields:

mysql> describe foo;
+-------+------------+------+-----+---------+----------------+
| Field | Type       | Null | Key | Default | Extra          |
+-------+------------+------+-----+---------+----------------+
| id    | bigint(20) | NO   | PRI | NULL    | auto_increment |
| bar   | longtext   | YES  |     | NULL    |                |
+-------+------------+------+-----+---------+----------------+
2 rows in set (0.00 sec) 

in PostgreSQL this yields:

foodb=> \d foo;
     Table "public.foo"
 Column |  Type  | Modifiers
--------+--------+-----------
 id     | bigint | not null
 bar    | text   |
Indexes:
    "pk_foo" PRIMARY KEY, btree (id)

According to the Java EE api:

The Lob type is inferred from the type of the persistent field or property

Which means that a field of type String should give you some text blob and a field of type byte[] should give you some binary blob.

Michael Lynch
  • 208
  • 1
  • 5
  • I tried this answer first, but as of 2017-02-02 with Ebean 9.3.1 with MySQL 5.7.17, `@Lob` yields `longblob` instead of `longtext`. Will that work with UTF-8? I think I'll go DB specific with `@Column(columnDefinition = "TEXT")` instead. – GlenPeterson Feb 02 '17 at 16:54