I got a minor problem with catching exceptions. I've got code like this:
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);
}
Hope the point of this is clear. If the default role does not yet exist an exception is supposed to be catched, the role is created and then it's given another shot. However I can't catch any exception.
The error log of first two exceptions thrown is:
[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 sess开发者_如何学编程ion
org.hibernate.exception.ConstraintViolationException: could not insert collection: [Comic.model.User.roles#5]
I guess I can't catch any exception since it's thrown outside my try block right? Any suggestions what could I do about this?
For your User entity I think your relationship to Role can/should be ManyToMany.
You should not need to manually be managing persisting the object graph, as you are doing in the catch block, if you place a CascadeType.PERSIST on that relationship as well.
If em.persist() throws and Exception. Then it seems strange that you would call the method again (twice) in your catch statement.
Either you need to add another try catch, inside your catch statement to deal with a second exception.
Or you need to change your logic to check for the need to persist the role first rather than handling it with Exception catching.
精彩评论