从jsr-303自定义验证器访问数据库 [英] Database access from jsr-303 custom validator

查看:131
本文介绍了从jsr-303自定义验证器访问数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将基于Spring的验证与由我的应用程序上下文中的以下功能启用的休眠验证器结合使用:

I'm using spring based validation in combination with hibernate validator enabled by the following in my application context:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        ....
        <property name="jpaPropertyMap">
            <map>
                <entry key="javax.persistence.validation.factory" value-ref="validator" />    
            </map>
        </property>
    </bean>

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

我已经实现了一个自定义验证器,该验证器使用弹簧注入的DAO访问数据库以检查特定对象的有效性约束.这会导致java.lang.StackOverflowError,因为每次从验证程序中从数据库加载对象时都会调用验证,这会导致无限循环.为了解决这个问题,我尝试在实体管理器上设置刷新模式,以使用以下代码从验证器中提交:

I've implemented a custom validator that accesses a database to check validity constraints for a particular object using a spring injected DAO. This results in a java.lang.StackOverflowError as it appears that the validation is called every time an object is loaded from the database from within the validator, causing an infinite loop. To get around this, I have tried setting the flush mode on my entity manager to commit from within the validator with the following code:

entityManager.setFlushMode(FlushModeType.COMMIT);

这会导致来自休眠状态的收集不由flush()处理"异常.

This results in an "collection not process by flush()" exception from hibernate.

是否存在从自定义验证器访问数据库的最佳实践示例,这将使我解决这两个问题?

Is there an example of best practice in accessing the database from within a custom validator which will allow me to get around both of these issues?

推荐答案

经过大量实验后,看来做到这一点的最佳方法是直接在代码内使用EntityManagerFactory.在验证器类的initialize(...)方法中,我具有以下代码:

After much experimentation, it would appear that the best way to do this to is to use the EntityManagerFactory directly from within the code. In the initialize(...) method of the validator class I have the following code:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu_name");
entityManager = emf.createEntityManager(); 

缺点是您没有获得Spring的DI功能,但是仍然可以访问数据库.

The downside is that you don't get Spring's DI features, but you can access the database nonetheless.

这篇关于从jsr-303自定义验证器访问数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆