使用hibernate 4.1.7,我有一个带有Collection(附件)的类,在映射文件中定义为:
<list lazy="false" table="news_attachment" name="attachments">
<cache usage="nonstrict-read-write"/>
<key column="news"/>
<index column="index_attachment"/>
<many-to-many class="mypackage.Archive" column="attachment" unique="true"/>
</list>
我正在尝试将两个元素交换为:
Archive archive0 = news.getAttachments().get(0);
Archive archive1 = news.getAttachments().get(1);
news.getAttachments().set(0, archive1);
news.getAttachments().set(1, archive0);
但是,在提交时,我得到了一个糟糕的
org.hibernate.exception.ConstraintViolationException: Duplicate entry '163703' for key 'attachment'
而且,令我惊讶的是,mysql更新是:
479 Query update news_attachment set attachment=163703 where news=53306 and index_attachment=0
479 Query update news_attachment set attachment=163703 where news=53306 and index_attachment=0
(惊喜是id和索引始终相同)。
但是,如果我创建一个新的List,按新顺序设置对象并执行setter,一切正常。
List<Archive> list = new ArrayList<Archive>();
list.add(news.getAttachments().get(1));
list.add(news.getAttachments().get(0));
news.setAttachments(list);
mysql.log按照我的预期输出插入,不同的ID和索引。
是否在原始列表中进行操作,不建议使用?