简体   繁体   中英

JPA, Hibernate - handling ContraintViolationException wrapped into RollbackException

I'm having problem processing ConstraintViolationException and RollbackException in JPA2 / Hibernate / Guice environment. Both exceptions occur while bean validation, but:

ConstraintViolationException is thrown when I try to persist a new entity

RollbackException occurs when I'm trying to merge the entity into context

This happens while form processing (both creating and updating entities) and catching these exceptions is tiresome:

try {
    // service.method is annotated with @Transactional
    entity = service.create(formEntity);
} catch (RollbackException re) {
    // occurs while merging the entity
    if (re.getCause() instanceof ConstraintViolationException) {
        errors.process((ConstraintViolationException) re.getCause());
    }
} catch (ConstraintViolationException cve) {
    // occurs while persisting the entity
    errors.process(cve);
}

I would not like to add another control flow and catching all RuntimeException s:

try {
    // bean validation fails (merge / persist)
} catch (RuntimeException ex) {
    if (errors.process(ex)) {
        // do something with entity
    }
}

Is it possible to somehow force hibernate to not wrap CVE into RE? What is the most transparent and DRY way of processing and handling such exceptions?

Thanks

hibernate将所有sql异常包装为RuntimeException (hibernate的特性)..你得到的是ConstraintViolationException可能是因为有一些字段不接受空值而你在插入时传递一个空值...(如果你不喜欢显式设置pojo属性的值,在插入时将其视为null)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM