从JSON创建Ebean:引用兄弟属性

时间:2016-04-12 08:48:07

标签: mysql json playframework ebean

使用PlayFramework 2.3.8和MySQL,我有一个简化的对象结构:

@Entity
@Table("ParentTable")
public class ParentClass extends AbstractModel{
  // ID is generated by MySQL, AI column

  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumn(name="child_1_id")
  public List<Child1> childs1 = new ArrayList<>(); // I am aware of the correct plural of the word 'child', I just don't care :)

  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumn(name="child_2_id")
  public List<Child2> childs2 = new ArrayList<>();
}

@Entity
@Table("Child1Table")
public class Child1Class extends AbstractModel{
  // ID is generated by MySQL, AI column
  // BUT I WANT TO REFERENCE THIS ID FROM CHILD2!

  @Column(name="some_property")
  String some_property;
}

@Entity
@Table("Child2Table")
public class Child2Class extends AbstractModel{
  // ID is generated by MySQL, AI column

  @Column(name="child1_id_reference")
  int child1_id_reference;
}

鉴于这个简单的模型,我想通过JSON字符串导入数据,并进一步创建具有关系的对象:

Example JSON:
{
childs1:[
  {
  "some_property": "foo"
  },{
  "some_property": "bar"
  }
],
childs2:[
  {
  "child1_id_reference": ??? // should reference to the ID of "foo"
  },{
  "child1_id_reference": ??? // should reference to the ID of "bar"
  }
]
}

最终,这个JSON被序列化并被泵入PlayFramework中的数据库:

JsonNode json = Json.parse(jsonIn); // jsonIn = the JSON above as String
ParentClass = Json.fromJson(json, ParentClass.class);

除了child1_id_reference属性外,它的工作正常。显然,我在编写JSON时无法知道“foo”和“bar”的未来ID。

所以问题是:我可以以某种方式链接那些,在JSON中引用兄弟(有时甚至是兄弟的孩子,在实际的数据模型中)吗?

或者你能想到一个解决方法吗?一个想法可能是为Child1Class提供一个属性,该属性包含一个在其ParentClass中唯一的值。在PlayFramework创建实际对象之后,Child1Class具有它的ID,而Child2Class可以在UPDATE语句中引用此ID。

这可行,还是我完全迷失在这里? “最坏的情况”是我必须在从JSON输入创建后手动连接Child1Class和Child2Class。提前致谢!

0 个答案:

没有答案