尝试使用Hibernate注释为一对多关系创建复合主键

时间:2013-09-16 23:31:09

标签: java mysql hibernate annotations one-to-many

我正在尝试使用带有注释的Hibernate3来建模单向OneToMany关系。方案是用户 有很多文章,文章许多用户。在工作流程中,用户可以阅读这些文章中的一篇,在这种情况下,我想将其移动到持久的“阅读”文章列表中。就Java模型而言,这就是发生一对多关系的地方。用户具有属于该个人用户的“阅读”文章列表。

问题是该表可以包含许多文章的许多用户,因此主键应该是user_id和article_id的组合。但是,在我当前的设置中,article_id被设置为主键。这就是创建一个错误,我可以在第一次准备就绪时将“读取”文章插入表中,但只要第二个用户尝试阅读该文章就会引发重复的键异常。

这是我的Java设置:

@JsonManagedReference
@OneToMany(fetch = FetchType.LAZY, orphanRemoval=true)
@JoinTable(name = "educational_article_read", joinColumns = {
    @JoinColumn(name = "user_id")}, inverseJoinColumns = {
    @JoinColumn(name = "article_id")})
@Cascade({CascadeType.ALL})
private List<EducationalArticleModel> articles_read = new ArrayList<EducationalArticleModel>();

以下是生成的表架构:

mysql> describe educational_article_read;
+------------+---------+------+-----+---------+-------+
| Field      | Type    | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| user_id    | int(11) | NO   | MUL | NULL    |       |
| article_id | int(11) | NO   | PRI | NULL    |       |
+------------+---------+------+-----+---------+-------+
2 rows in set (0.05 sec)

错误堆栈跟踪:

org.springframework.dao.DataIntegrityViolationException: Duplicate entry '55' for key 'article_id'; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Duplicate entry '55' for key 'article_id'
    at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:138)
    at org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:594)
    at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:476)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:387)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
    at com.bosch.dao.UserDAO$$EnhancerByCGLIB$$f17df281.update(<generated>)

0 个答案:

没有答案