【发布时间】:2014-02-08 02:57:17
【问题描述】:
我在谷歌上搜索了一下,时间不多了,所以我把它扔在这里,希望有人知道答案。我有一个系统,我在服务层有弹簧事务边界。下面是道层。我已经对我的模型对象进行了 bean 验证,并且我已经将 DAO 包装在编译时方面j 围绕方面,如下所示:
@Aspect
public class ValidationCollectorAspect {
@Around("daoMethods()")
public Object collectDaoMessages(ProceedingJoinPoint thisJoinPoint) throws Throwable {
try {
return thisJoinPoint.proceed();
} catch (ConstraintViolationException e) {
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
List<UserMessage> userMessages = ThreadContext.MESSAGES.get();
for (ConstraintViolation<?> constraintViolation : constraintViolations) {
userMessages.add(new UserMessage(constraintViolation.getMessage(), MessageType.VALIDATION));
}
throw new MyPersistenceException("Validation failures", e);
}
}
@Pointcut("call(public * *(..)) &&!call(* getEntityManager()) && within(com.myclient.dao.impl..*)")
public void daoMethods() {
}
}
问题是验证似乎发生在事务提交时,而不是在 DAO 中的保存或更新操作之前。这意味着来自 bean 验证的 ConstraintViolationException 直到在服务方法返回之后并且在此连接点之后才被抛出。我的证据是 stack trace 不包含任何 dao 服务方法。我编写的代码的第一种方法由
显示 at com.myclient.servlet.rest.Rest.updateObjects(Rest.java:323)
但这是一个 servlet 名称 Rest 上的方法,重点是不需要为系统中各种 servlet 上的一大堆特定方法创建连接点,并且还能够处理约束冲突在它被包裹在任意层的弹簧异常之前。
我知道有时在提交之前验证所有休眠更改的总和可能很酷,但这不是我想要的。 (虽然作为第二轮验证不会不受欢迎)当我在 dao 中调用 hibernate save 或 update 方法时,而不是在事务提交时,如何告诉 hibernate 验证器处理验证?
这是我构建的东西的版本:
compile 'org.hibernate:hibernate-entitymanager:4.2.2.Final'
compile 'org.hibernate:hibernate-validator:5.0.1.Final'
compile 'org.hibernate:hibernate-c3p0:4.2.2.Final'
compile 'org.springframework:spring-orm:3.2.3.RELEASE'
compile 'org.springframework:spring-context:3.2.3.RELEASE'
compile 'org.springframework:spring-web:3.2.3.RELEASE'
compile 'javax.inject:javax.inject:1'
compile 'org.aspectj:aspectjrt:1.7.3'
ajc "org.aspectj:aspectjtools:1.7.3"
编辑:进一步说明...我在 JPA 下完成所有这些工作,因此如果存在非休眠特定解决方案,我更喜欢它。
【问题讨论】:
标签: java spring hibernate aspectj bean-validation