在play框架中持久化对象列表

时间:2015-04-16 19:14:30

标签: java playframework ebean

我有一个名为Device.class的类,我希望有一个CommentObj.class列表的字段。问题是这个字段没有保存在数据库中(我使用Ebean)。怎么可能这样做?

@Entity
public class Device extends Model {

@Id
public Long id;

@Constraints.MaxLength(50)
@Constraints.Required
public String serialNo;

...

public List<CommentObj> comments = new ArrayList<CommentObj>();

public class CommentObj extends Model {

@Id
public Long id;


@Constraints.MaxLength(50)
public String author;

@Constraints.MaxLength(500)
@Constraints.Required
public String content;

@Constraints.Required
public Date date;

public static Finder<Long, CommentObj> find = new Finder<>(Long.class, CommentObj.class);

public CommentObj(String author, String content){
    this.author = author;
    this.content = content;
    date = new Date();
}

}

这是数据库中Device的结构(根据1.sql)。没有评论栏的标志

create table device (
  id                        bigint not null,
  serial_no                 varchar(255),
  invent_no                 varchar(255),
  name                      varchar(255),
  device_type_id            bigint,
  description               varchar(2000),
  cal_date                  timestamp,
  cal_duration_in_months    integer,
  setup_id                  bigint,
  manufacturer_id           bigint,
  constraint pk_device primary key (id))
;

1 个答案:

答案 0 :(得分:1)

假设您的comment_obj表中有device_id,您可以通过向Device.class&#39;添加以下注释来实现单向OneToMany映射。 comments字段:

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(referencedColumnName = "id", name = "device_id")
public List<CommentObj> comments = new ArrayList<CommentObj>();