I have an entity with a field name, and I want it to be not longer than 255, so I defined it like this:
@Entity
public class A implements Serializable {
...
@NotNull
@Size(max=255)
private String name;
I want it to be validated as I call a.persist(), so that if name is too long an exception is thrown.
I have HibernateValidator defined in validation.xml:
<?xml version="1.0" encoding="UTF-8"?>
<validation-config
xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-1.0.xsd">
<default-provider>org.hibernate.validator.HibernateValidator</default-provider>
<message-interpolator>org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator</message-interpolator>
<traversable-resolver>org.hibernate.validator.engine.resolver.DefaultTraversableResolver</traversable-resolver>
<constraint-validator-factory>org.hibernate.validator.engine.ConstraintValidatorFactoryImpl</constraint-validator-factory>
</validation-config>
Yet it does not work. No exception is thrown during persist, and only during commit, when the entity manager is flushed, do I get an exception, and even then it is an exception from the database (because it too has a limitation on the column with size 255). So I believe that my validation is not working at all.
So I'd be glad if you helped me with those two questions: 1) how to make the validation happen during persist and not during flush 2) how cause the validation to throw exceptions when validation fails?
You can use Hibernate validator .
you have to turn on pre-update and pre-insert events for BeanValidationEventListener
.
you can read more about it here and here.
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With