views:

289

answers:

2

Hi.

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 {
...
+3  A: 

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.

Pascal Thivent
Thank you for answer, Pascal. Yes ,validation should be performed on SQL result. The flow is following - in case result of query is not empty, that transaction for this entity should be performed.
sergionni
@sergionni You're welcome. But I'm afraid Bean Validation is not be the right tool for your flow. AFAIK, Bean Validation is for, well, bean validation, not query result validation.
Pascal Thivent
Thanks ,Pascal,i've updated post (added entity class part). So, possible step is to develope one more class,someth. like CurrencyValidator ,in which i should implement getNamedQuery("isValutaKursExists")?
sergionni
+3  A: 

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

Hardy