[英]How to populate a ManyToMany relationship using YAML on Play Framework 2.1.x
I have the following ManyToMany (bidirectional) relationship: 我有以下ManyToMany(双向)关系:
@Entity
public class Proposal extends Model {
...
@ManyToMany
public List<Tag> tags;
}
@Entity
public class Tag extends Model {
...
@ManyToMany(mappedBy="tags")
public List<Proposal> taggedProposals;
}
And I want to populate my DB with some test data using a yaml file (to display later using a simple view). 我想使用yaml文件(稍后使用简单视图显示)使用一些测试数据填充我的数据库。 This is part of my yaml file:
这是我的yaml文件的一部分:
...
- &prop2 !!models.Proposal
id: 2
title: Prop2 title
proposer: *user2
- &prop3 !!models.Proposal
id: 3
title: Prop3 title
proposer: *user3
# Tags
- &tag1 !!models.Tag
name: Tag1 name
desc: Tag1 description
taggedProposals:
- *prop1
- &tag2 !!models.Tag
name: Tag2 name
desc: Tag2 description
taggedProposals:
- *prop2
- *prop3
The problem is that when I try to display a Proposal's tags
or a Tag's taggedProposals
, the ArrayLists are empty! 问题是,当我尝试显示Proposal的
tags
或Tag的taggedProposals
,ArrayLists是空的! I tried using square brackets and commas without success. 我尝试使用方括号和逗号但没有成功。 All the other data is being loaded and displayed correctly.
正在加载和显示所有其他数据。
The problem you have encountered happens because play uses ebean and ebean doesn't automagically saves many-to-many associations. 您遇到的问题是因为Play使用ebean而ebean不会自动保存多对多关联。
I had to solve it this way: 我必须这样解决它:
private static void initialData() {
@SuppressWarnings("unchecked")
Map<String,List<Object>> all = (Map<String,List<Object>>) Yaml.load("initial-data.yml");
// Save all roles
Ebean.save(all.get("roles"));
// Insert users and for every user save its many-to-many association
Ebean.save(all.get("users"));
for(Object user: all.get("users")) {
Ebean.saveManyToManyAssociations(user, "roles");
}
}
And the yaml file: 和yaml文件:
# Roles
roles:
- &adminRole !!models.Role
name: admin
- &projectleadRole !!models.Role
name: projectlead
# Users
users:
- &leonUser !!models.User
email: leon@domain.com
roles:
- *adminRole
- *projectleadRole
firstName: Leon
lastName: Radley
If the answer posted by Leon Radley was accurate, it is no longer the case ! 如果Leon Radley发布的答案是准确的,那就不再是这样了! Play evolved and, since the 2.1 version, manyToMany reference initialization by list now work ( see this link ) !
Play进化了,自2.1版本开始,很多ToMany引用按列表初始化工作( 见此链接 )! See User.zones for an example of how it works.
有关其工作原理的示例,请参阅User.zones。
zones:
- &zone1 !!models.Zone
id: 1
gtbName: "ZZ01"
- &zone2 !!models.Zone
...
users:
- &user4 !!models.User
id: 4
profile: *profile4
defaultZone: *zone3
zones:
- *zone1
- *zone2
- *zone3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.