问题
I have the following ManyToMany (bidirectional) relationship:
@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). This is part of my yaml file:
...
- &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! I tried using square brackets and commas without success. All the other data is being loaded and displayed correctly.
回答1:
If the answer posted by Leon Radley was accurate, it is no longer the case ! Play evolved and, since the 2.1 version, manyToMany reference initialization by list now work (see this link) ! See User.zones for an example of how it works.
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
回答2:
The problem you have encountered happens because play uses ebean and ebean doesn't automagically saves many-to-many associations.
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:
# 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
来源:https://stackoverflow.com/questions/18298173/how-to-populate-a-manytomany-relationship-using-yaml-on-play-framework-2-1-x