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

假装没事ソ 提交于 2019-12-07 06:25:40

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8820067/how-can-i-validate-constrains-on-entities-during-persist-of-an-entity-in-hiberna

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!