【发布时间】:2011-08-15 11:45:55
【问题描述】:
我使用 JPA->Hibernate。播放框架。我想有关系。
Category - 1:n -> Tag
每个类别可以有很多标签,但标签不知道。
所以,我喜欢这样:
@Entity public class Category ... { @OneToMany public List<Tag> tags = new LinkedList<Tag>(); }
我有测试:
@测试 公共无效 playWithTags() {
Tag tag1 = new Tag("tag1").save(); // managed by playframework
Category cat1 = new Category("cat1");
cat1.tags.add(tag1);
cat1.save();
// check if tag1 and cat1 were saved
assertEquals(1, Tag.count());
assertEquals(1, Category.count());
Category cat2 = new Category("cat2");
cat2.tags.add(tag1);
cat2.save();
}
结果是:
16:18:01,555 ERROR ~ Duplicate entry '1' for key 'tags_id'
16:18:01,555 ERROR ~ Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelp
....
java:908)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.sql.BatchUpdateException: Duplicate entry '1' for key 'tags_id'
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2020)
似乎 cat2.save() 尝试做的比它应该做的更多
如果使用 merge() 而不是 save() 效果很好:
cat2.merge();
但是为什么?
【问题讨论】:
标签: database hibernate jpa playframework