通过使用以下代码将其添加到配置中来使用知道休眠会话的自定义ConstraintValidatorFactory
会导致对该工厂负责的任何操作(创建、更新)进行双重验证。
这个例子中的验证器ValidBeanDatabase
被不同的实例调用了两次。所有其他约束都验证一次(@ValidBean
例如)。
工厂和验证器的实现与本文中的类似:
https ://community.jboss.org/wiki/AccessingTheHibernateSessionWithinAConstraintValidator
验证.xml
<constraint-validator-factory>package.SessionConstraintValidatorFactory</constraint-validator-factory>
<constraint-mapping>package/Bean-validation.xml</constraint-mapping>
爪哇:
final Configuration configuration = new Configuration().configure();
// get ValidatorFactory from validation.xml
final ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure()
.buildValidatorFactory();
// ... add SessionFactory to custom ConstraintValidatorFactory
((SessionConstraintValidatorFactory)validatorFactory.getConstraintValidatorFactory()).setSessionFactory(sessionFactory);
// set ValidatorFactory
configuration.getProperties().put("javax.persistence.validation.factory", validatorFactory);
豆:
@GroupSequence(value =
{
Bean.class, Create.class
})
@ValidBean // custom class-level constraint
public class Bean
{
// properties and validator annotations
}
Bean-validation.xml
通过 xml 映射添加 Hibernate 会话感知约束。
<bean class="Bean" ignore-annotations="false">
<class>
<constraint annotation="package.ValidBeanDatabase">
<groups>
<value>package.groups.Create</value>
</groups>
</constraint>
</class>
</bean>
编辑:
休眠配置
<property name="javax.persistence.validation.group.pre-persist">
javax.validation.groups.Default, package.groups.Create
</property>
Glassfish 3.1.2 与 Hibernate Validator 4.2
@Gunner 您在其他地方是否有任何与验证相关的配置,例如persistence.xml? 不