How can I define 'TEXT' type using eBean in Play! framework?
Asked Answered
A

2

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!

Arun answered 10/9, 2012 at 3:30 Comment(0)
T
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.

Trichroism answered 10/9, 2012 at 6:58 Comment(1)
It is not correct for Oracle for example. An alternative there is "Clob"Indianapolis
V
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.

Virescent answered 1/10, 2012 at 8:30 Comment(1)
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.Hilarity

© 2022 - 2024 — McMap. All rights reserved.