Question

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")
public class Currency {
...
Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top