Hibernate会话在ConstraintViolationException之后失效 [英] Hibernate Session is invalidated after ConstraintViolationException
问题描述
有没有办法在约束违反异常被抛出后继续使用线程绑定的hibernate会话?我在这里给出一个简短的例子:
Parent other = service.load(33); //加载一个新父母
尝试{
Parent p = new Parent();
p.setName(A name);
service.save(p); //一个@Transactional弹簧服务类,抛出ConstraintViolationException - 名称应该至少有15个字符长
} catch(ConstraintViolationException e){
//我想处理验证错误并正常执行
//但会话已经在此处关闭
}
System.out.println(Children:+ other.getChildren()); //延迟初始化异常,即使使用opensessioninview
从现在开始,hibernate会话完全没用,甚至适用于只读操作,例如使用OpenSessionInView模式在视图中呈现延迟集合。
会话的文档声明如果Session引发异常,则事务必须回滚并会话被丢弃。发生异常后,会话的内部状态可能与数据库不一致。。 AFAIK,没有办法从此恢复,我记得有人在工作,警告我不要使用session-per-request / OpenSessionInView模式,因为这些类型的问题。
Is there any way to continue using an thread bound hibernate session after constraintviolation exception has been thrown? I'm giving a short example here:
Parent other=service.load(33); // loads a new parent
try {
Parent p=new Parent();
p.setName("A name");
service.save(p); // a @Transactional spring service class, throws ConstraintViolationException - name should be at least 15 characters long
} catch (ConstraintViolationException e){
// i would like to handle validation errors and proceed normally
// but the session is allready closed here
}
System.out.println("Children: " + other.getChildren()); // lazy initialization exception, even when using opensessioninview
From now on the hibernate session is completely useless, even for read-only operations like rendering a lazy collection in view using OpenSessionInView pattern.
Session's documentation states that If the Session throws an exception, the transaction must be rolled back and the session discarded. The internal state of the Session might not be consistent with the database after the exception occurs..
AFAIK, there's no way to recover from this, I recall someone at work warning me not to use the session-per-request/OpenSessionInView-pattern because of these kinds of problems.
这篇关于Hibernate会话在ConstraintViolationException之后失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!