在我的部分代码中,我通过 Hibernate 从数据库中获取一个对象,更改一个字段并提交更改
session = HibernateUtil.beginTransaction();
Song song =SongCache.loadSongFromDatabase(session, songId);
song.setLastModified(new Date(new File(song.getFilename()).lastModified() + 1));
session.saveOrUpdate(song);
session.getTransaction().commit();
歌曲类定义为,我也使用 Hibernate Envers 并且歌曲被审计
/**
* A Song (or sound recording)
*/
@Audited
@Entity
public class Song
{
@Id
@GeneratedValue
private Integer recNo;
@Version
private int version;
@Basic
private String filename;
/**
* Last Modified Date
*/
@Temporal(TemporalType.TIMESTAMP)
private Date lastModified;
public Song(String file)
{
this.setFilename(file);
}
public Song()
{
}
@Column(length = 1000)
private String album;
......
}
但有时我得到一个 StaleObjectStateException,我无法理解这是怎么发生的
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.jthink.songlayer.Song#1]
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:2359)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3010)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2908)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3237)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:113)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:272)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:264)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:187)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1081)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:315)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at com.jthink.buzikmusik.analyse.analyser.SongSaver.saveSongToFile(SongSaver.java:286)
at com.jthink.buzikmusik.analyse.analyser.SongSaver.saveChanges(SongSaver.java:75)
at com.jthink.buzikmusik.analyse.analyser.SongSaver.call(SongSaver.java:70)
at com.jthink.buzikmusik.analyse.analyser.SongSaver.call(SongSaver.java:45)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)