Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate constrains on entities during persist of an entity in hibernate

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?

like image 442
alexander zak Avatar asked Oct 10 '22 00:10

alexander zak


1 Answers

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.

like image 116
danny.lesnik Avatar answered Oct 13 '22 09:10

danny.lesnik