如何在hibernate中保留实体期间验证实体上的约束 [英] How can I validate constrains on entities during persist of an entity in hibernate

查看:206
本文介绍了如何在hibernate中保留实体期间验证实体上的约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带字段名称的实体,我希望它不超过255,所以我这样定义:

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;

我希望它在我调用a.persist()时得到验证,所以如果名字也是抛出一个异常。

I want it to be validated as I call a.persist(), so that if name is too long an exception is thrown.

我在validation.xml中定义了HibernateValidator:

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>

然而它不起作用。在持久化期间不会抛出异常,并且仅在提交期间,当刷新实体管理器时,我是否得到异常,即使这样,它也是数据库中的异常(因为它对大小为255的列也有限制)。所以我相信我的验证根本不起作用。

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.

所以如果你帮助我解决这两个问题,我会很高兴:
1)如何在持久化期间进行验证而不是在刷新期间进行验证
2)如何在验证失败时导致验证抛出异常?

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?

推荐答案

您可以使用 Hibernate验证器

你必须为 BeanValidationEventListener 开启预更新和预插入事件。

you have to turn on pre-update and pre-insert events for BeanValidationEventListener.

你可以了解更多信息此处这里

you can read more about it here and here.

希望有所帮助。

这篇关于如何在hibernate中保留实体期间验证实体上的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆