这里我提供了抛出异常的hibernate项目代码
例外:
org.hibernate.StaleObjectStateException:Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect):
当我们调用下面提到的方法时 我想让这个线程安全
public String saveAnswer(String assignmentid, String answerid, String answer) throws Exception {
getStudentManager().logRequestedAnswer(answerid, answer);
User user = getUserManager().getCurrentUser();
HttpSession session = WebContextFactory.get().getSession();
int practiceElapsedTime = getStudentManager().touchPracticeTime(assignmentid, session);
long practiceUpdateTime = ((Date) session.getAttribute("student_current_practice_last_update")).getTime();
StudentAnswer savedAnswer = getStudentManager().saveAnswer(user, assignmentid, answerid, answer);
Map<String, Object> result = new HashMap<String, Object>();
result.put("answerid", savedAnswer.getAnswerKey().getObjectid());
result.put("answer", savedAnswer.getAnswer());
//we're synching the client's time with the server on saves
result.put("practiceElapsedTime", practiceElapsedTime);
result.put("practiceUpdateTime", practiceUpdateTime);
if (savedAnswer.getAssignmentStatus().isCompleted())
result.put("progress", savedAnswer.getAssignmentStatus().getPercent());
else
result.put("progress", savedAnswer.getAssignmentStatus().getProgress());
StringWriter json = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(json, result);
return json.toString();
}
答案 0 :(得分:1)
我用hibernate学到了两件事。 首先,如果快速多次保存同一个对象,则可能会出现StaleObjectStateException。这是由于桌面上的版本控制。一个简单的解决方案是禁用它。 如果您的表由多个线程访问,您应该考虑锁定:http://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch05.html
答案 1 :(得分:0)
这可能意味着在您的事务提交之前,您尝试更新的行已经被其他一些线程更新过。检查多个线程是否同时处理相同的记录。