我剛剛開始使用Play框架,並且遇到了在我的模型類中使用集合的一些問題。我對Play和JPA/Hibernate很新,所以請原諒我的noobness ...我試過在網上尋找答案,但是找不到我要找的東西。Play框架和模型類中的集合的使用
從本質上講,我有2種型號:
@Entity
public class Song extends Model
{
@Column(unique = true)
public int songId;
public String name;
public String artist;
public Song() {}
public Song(int songId, String name, String artist)
{
this.songId = songId;
this.name = name;
this.artist = artist;
}
}
@Entity
public class CurrentSongList extends Model {
@OneToMany(orphanRemoval=false)
public List<Song> currentSongList;
}
我想這裏是擁有數據庫中的所有歌曲,然後在列表中暫時保持這些歌曲的子集(列表中的內容會隨着時間而改變)...如果列表被刪除,我不希望歌曲被刪除(歌曲不應該包含對列表的任何引用)。然後,我嘗試在應用程序啓動時執行的操作是從數據文件加載歌曲,並將歌曲的子集插入到列表中,並使用下面的代碼保存列表....這是我遇到無窮無盡問題的地方。
Fixtures.deleteDatabase();
Fixtures.loadModels("songlist.yaml");
List<Song> songs = Song.findAll();
CurrentSongList.deleteAll();
CurrentSongList currentSongs = new CurrentSongList();
currentSongs.currentSongList = new ArrayList<Song>();
currentSongs.currentSongList.add(songs.get(0));
currentSongs.currentSongList.add(songs.get(1));
EntityManager em = JPA.em();
em.persist(currentSongs);
em.flush();
如果我省略了flush調用,那麼稍後從DB中獲取其內容時,列表似乎不會保存。然而,刷新調用導致以下異常:
Caused by: org.hibernate.HibernateException: Found two representations of same collection: models.CurrentSongList.currentSongList
at org.hibernate.engine.Collections.processReachableCollection(Collections.java:175)
at org.hibernate.event.def.FlushVisitor.processCollection(FlushVisitor.java:60)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:122)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:83)
at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:77)
at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:165)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:240)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
我意識到我可能做一些愚蠢的這裏(?是的flush()的持續確需後),不明白這東西是如何工作的正常,然而,我一直在努力尋找關於這個確切問題的信息。任何幫助我應該如何去實現上述將不勝感激。
謝謝!
發佈songlist.yaml – Ryan