Play Framework 2 Ebean specify default value for field
Asked Answered
L

2

7

I have a simple model in Play Framework 2, and I would like to specify a default value to be inserted on a specify INT column if none is provided when the INSERT is performed.

Model:

@Entity
@Table(name = "DashboardOptions", schema = "dbo")
public class DashboardOptions extends Model implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    public Long id;

    @Basic(optional = false)
    @Column(name = "userId")
    public Long userId;

    @Column(name = "chartType")
    public String chartType;

    public String name;

    public Integer size = 2;

I'd like to have the size column populate with 2 by default, however, if I specify the default value as above, my database evolution does not reflect this:

create table dbo.DashboardOptions (
id                        numeric(19) identity(1,1) not null,
userId                    numeric(19) not null,
chartType                 varchar(255),
name                      varchar(255),
size                      integer,
constraint pk_DashboardOptions primary key (id))
;

What I would expect to see is this:

create table dbo.DashboardOptions (
id                        numeric(19) identity(1,1) not null,
userId                    numeric(19) not null,
chartType                 varchar(255),
name                      varchar(255),
size                      integer default 2,
constraint pk_DashboardOptions primary key (id))
;
Lido answered 4/2, 2014 at 15:9 Comment(0)
P
12

Use own columnDefinition like this:

@Column(columnDefinition = "integer default 2")
public Integer size = 2;
Paulitapaulk answered 4/2, 2014 at 16:9 Comment(1)
Brilliant, that did it! Thanks a bunch. I had seen (and even used) column definition before, but I thought it was limited to specifying ONLY the datatype of the column. Perfect answer!Lido
F
0

Another option is to use @PrePersist tag package javax.persistence. you can have a method decorated in your bean with @PrePersist and that method is called before Ebean.save call. so in this case the following code would set the default value of size to 2.

@PrePersist
protected void onCreate {
  if (this.size == null)
          this.size = 2;
}

This approach is applicable only within the context of ORM (Ebean) and obviously wouldn't work directly with SQL. The advantage of this method is that this is more database neutral in the sense that integer default 2 might not be a valid column definition string in some unknown strange RDBMS systems.

Fina answered 24/5, 2016 at 18:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.