我有这样的服务:
@Service
public class UserEventServiceImpl implements UserEventService {
@Autowired
UserEventDao userEventDao;
@Override
public UserEvent getOrCreateUserEvent(String guid) {
return userEventDao.getOrCreateUserEvent(guid);
}
@Override
public void updateUserEvent(UserEvent userEvent) {
userEventDao.update(userEvent);
}
@Override
public void processEventType(String guid, EventType type) {
UserEvent userEvent = getOrCreateUserEvent(guid);
switch (type) {
case DOWNLOAD_STARTED: {
userEvent.setDownloadInstallStarted(new Date());
updateUserEvent(userEvent);
break;
}
case DOWNLOAD_COMPLETE: {
userEvent.setDownloadInstallCompleted(new Date());
updateUserEvent(userEvent);
break;
}
case UPDATE_DOWNLOAD_STARTED: {
userEvent.setDownloadUpdateStarted(new Date());
updateUserEvent(userEvent);
break;
}
case UPDATE_DOWNLOAD_FINISHED: {
userEvent.setDownloadUpdateCompleted(new Date());
updateUserEvent(userEvent);
break;
}
case UPDATE_COMPLETE: {
userEvent.setUpdateCompleted(true);
updateUserEvent(userEvent);
break;
}
}
}
}
这样的dao类:
@Repository
public class UserEventDaoHb extends BaseDaoHb<UserEvent> implements UserEventDao {
public UserEventDaoHb() {
super(UserEvent.class);
}
@Override
public UserEvent getOrCreateUserEvent(String guid) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {
date = formatter.parse(formatter.format(date));
} catch (ParseException e) {
//do nothing. Impossible to happen
}
UserEvent event = findOneByParams(Restrictions.eq("guid", guid), Restrictions.eq("date", date));
if (event == null) {
event = new UserEvent();
event.setGuid(guid);
event.setDate(date);
getHibernateTemplate().save(event);
getHibernateTemplate().flush();
}
return event;
}
}
UserEvent是一个简单的POJO对象。 此代码在本地和测试服务器上运行良好,但是当我在生产中运行它时会导致此类异常:
ERROR [http-apr-8080-exec-55] - 2014-06-20 07:27:14 - (BatchingBatcher.java:73) - 异常执行批处理: org.hibernate.StaleStateException:批量更新从update [0]返回意外的行数;实际行数:0;预期:1
据我了解,它发生的原因是因为当更新应该在DB中时,UserEvent还不存在。 有任何想法如何解决它?
答案 0 :(得分:0)
我忘记将 @Transactional 注释添加到 getOrCreateUserEvent()方法。