开发者

Configure Hibernate validation for bean

I need to perform validation based on SQL query result.

Query is defined as annotation - as @NamedQuery in my entity bean.

According to Hibernate documentation(doc), there is possibility to validate bean on following operations:

pre-update

pre-insert

pre-delete

looks like:

<hibernate-configuration>
    <session-factory>
       ...
    <event type="pre-update">
       <listener class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"/>
    </event>
    <event type="pre-insert">
        <listener class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"/>
    </event>
    <event type="pre-delete">
        <listener class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"/>
    </event>
</hibernate-configuration>

The question is how to connect my bean with the validation configuration, described above.

updated:

entity class

...
@Entity
@NamedQuery(name = "isValutaKursExists", query = "SELECT id FROM CurrencyRate WHERE bankId = :bankNum")
@Table(name = "Currency")
pub开发者_如何学JAVAlic class Currency {
...


The question is how to connect my bean with the validation configuration, described above.

You need to annotated you bean with annotations from the Bean Validation API to add constraints like @NotNull, @Size (built-in) or to define your own. But Bean Validation is not really meant to perform validation based on SQL query result.

By the way, you mentioned @NamedQuery so I guess you are using Hibernate EntityManager. In that case, I would recommend integrating Bean Validation with JPA (instead of Hibernate). If you are using JPA 2.0, just put the Bean Validation implementation on the classpath. If you're using JPA 1.0, refer to this previous answer.


Yes, the right approach would be a custom constraint like ValidCurrency and a matching ValidCurrencyValidator. You will need access to your Hibernate Session resp. EntityManager in your ConstraintValidator implementation. You can get some ideas on how to do this on the Hibernate wiki - Accessing the Hibernate Session within a ConstraintValidator

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜