hibernate 4.1.7を使用して、マッピングファイルで次のように定義されたコレクション(添付ファイル)を持つクラスがあります。
<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>
私は2つの要素を次のものと交換しようとしています:
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とindexは常に同じです)。
しかし、新しいリストを作成し、オブジェクトを新しい順序で設定してセッターを実行すると、すべてが正常に機能します。
List<Archive> list = new ArrayList<Archive>();
list.add(news.getAttachments().get(1));
list.add(news.getAttachments().get(0));
news.setAttachments(list);
mysql.logは、期待どおりに挿入を出力し、さまざまなIDとインデックスを出力します。
元のリストでの操作はお勧めしませんか?