Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 播放框架2可以为字段指定默认值_Java_Ebean_Playframework 2.2_Playframework Evolutions - Fatal编程技术网

Java 播放框架2可以为字段指定默认值

Java 播放框架2可以为字段指定默认值,java,ebean,playframework-2.2,playframework-evolutions,Java,Ebean,Playframework 2.2,Playframework Evolutions,我在Play Framework 2中有一个简单的模型,如果在执行插入时没有提供任何值,我想在specify INT列上指定要插入的默认值 型号: @Entity @Table(name = "DashboardOptions", schema = "dbo") public class DashboardOptions extends Model implements Serializable { private static final long serialVersionUID =

我在Play Framework 2中有一个简单的模型,如果在执行插入时没有提供任何值,我想在specify INT列上指定要插入的默认值

型号:

@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;
我希望默认情况下使用
2
填充
size
列,但是,如果我如上所述指定默认值,则我的数据库演变不会反映这一点:

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))
;
我希望看到的是:

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))
;

使用自己的
columnDefinition
如下:

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

另一个选项是使用
@PrePersist
标记包
javax.persistence
。您可以在bean中使用
@PrePersist
修饰一个方法,并且在Ebean.save调用之前调用该方法。因此,在这种情况下,下面的代码会将size的默认值设置为2

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

这种方法只适用于ORM(Ebean)上下文,显然不能直接与SQL一起工作。这种方法的优点是,它与数据库更加无关,因为在某些未知的奇怪RDBMS系统中,
integer default 2
可能不是有效的列定义字符串。

Brilliant,就是这样!非常感谢。我以前看过(甚至使用过)列定义,但我认为它仅限于指定列的数据类型。完美答案!