我在捕获异常时遇到了一个小问题。我有这样的代码:
Role r=new Role("default");
r.setId(Role.DEFAULT_ID);
u.getRoles().add(r); // u is instance of entity which is in relation manytomany with r
try{
em.persist(u);
}catch(Exception e){
System.out.println(e.getClass().getName()+" - default role not found, creating...");
em.persist(r);
em.persist(u);
}
希望这一点很清楚。如果默认角色尚不存在,则应该捕获异常,创建该角色,然后再给它一次机会。但是我无法捕捉到任何异常。
前两次抛出的异常的错误日志为:
[org.hibernate.util.JDBCExceptionReporter] (http-127.0.0.1-8080-5) could not insert collection: [Comic.model.User.roles#5] [insert into USER_ACCOUNT_ROLE (USER_ACCOUNT_uid, roles_rid) values (?, ?)]
java.sql.SQLIntegrityConstraintViolationException: ...blabla you dont follow constraints
.
ERROR [org.hibernate.event.def.AbstractFlushingEventListener] (http-127.0.0.1-8080-5) Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: could not insert collection: [Comic.model.User.roles#5]
我想我无法捕捉到任何异常,因为它被抛到了我的 try block 之外,对吗?有什么建议我可以做些什么吗?
最佳答案
对于您的 User 实体,我认为您与 Role 的关系可以/应该是 ManyToMany。
如果放置 CascadeType.PERSIST,则无需像在 catch block 中那样手动管理持久化对象图。关于这种关系也是如此。
关于java - 处理持久性异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6358246/