我已经发现several https://stackoverflow.com/questions/6033314/use-map-as-property-of-model-in-play 问题 https://stackoverflow.com/questions/7002129/play-framework-and-the-use-of-collections-in-model-classes about https://stackoverflow.com/questions/8318692/hibernateexception-found-two-representations-of-same-collection这个,但没有一个对问题以及如何调试它的完整解释 - 答案都是轶事。
问题是,在 Play 1.2.4 JPA 测试中,当我save()
一个模型:
org.hibernate.HibernateException:找到相同的两个表示
集合:models.Position.projects
我想知道:
- 是否有与 Play 无关的一般问题的文档?问题出在休眠状态,但 Google 的很多结果都在 Play 应用程序中。
- 避免此问题的一些基本最佳实践有哪些?
- 是玩游戏造成的吗?或者我做错了什么?
- 针对我的具体情况如何解决?
这是 github 上问题的重现 https://github.com/ripper234/play-two-representation-same-collection。我有四个实体:
@Entity
public class Person extends Model {
public String name;
@OneToMany(cascade = CascadeType.ALL)
public List<Position> positions;
}
@Entity
public class Position extends Model {
public Position(){}
public Position(Company companies) {
this.companies = companies;
this.projects = new ArrayList<Project>();
}
@OneToOne
public Company companies;
@ManyToOne
public Person person;
@OneToMany
public List<Project> projects;
}
@Entity
public class Company extends Model {
public String name;
}
@Entity
public class Project extends Model {
public Project(){}
public Project(String field, String status){
this.theField = field;
this.status = status;
}
@ManyToOne
public Position position;
public String theField;
public String status;
}
和我的持久性代码:
Company facebook = new Company();
facebook.name = "Facebook";
facebook.save();
Company twitter = new Company();
twitter.name = "Twitter";
twitter.save();
Person joe = new Person();
joe.name = "Joe";
joe.save();
joe.positions = new ArrayList<Position>();
Position joeAtFacebook = new Position(facebook);
joeAtFacebook.projects.add(new Project("Stream", "Architect"));
joeAtFacebook.projects.add(new Project("Messages", "Lead QA"));
joe.positions.add(joeAtFacebook);
Position joeAtTwitter = new Position(twitter);
joeAtTwitter.projects.add(new Project("Steal stuff from Facebook", "CEO"));
joe.positions.add(joeAtTwitter);
joe.save();
顺便说一句,我尝试添加玩关联模块 http://www.playframework.org/modules/associations-1.0.1/home正如一个人所建议的,这似乎没有帮助。
我发现创建的表在某种意义上确实是重复的:
我有两个person_position
表和一个position table
,其中两者都包含相似的字段:person_position
包含一个Person_id
and positions_id
,而position
表包含id
(意思是位置ID),person_id
, and companies_id
。所以我知道我的模型定义创建了某种意外的冗余,但我并不真正了解如何解决它。
我认为这可能与双向映射有关,但这是一个模型是单向的分支 https://github.com/ripper234/play-two-representation-same-collection/tree/no-bidirectional(我删除了一些反向引用) - 但问题仍然发生。