Domanda

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))
;
È stato utile?

Soluzione

Use own columnDefinition like this:

@Column(columnDefinition = "integer default 2")
public Integer size = 2;

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top