How would I specify a Hibernate “@Pattern” annotation using a regular expression from a .properties file or database

只愿长相守 提交于 2019-12-03 14:23:08

Within annotations you can only refer to constant expressions, so loading values from a property file or database wouldn't work here.

You could use the API for dynamic constraint declaration introduced in Hibernate Validator 4.2 which allows to define constraints at runtime. Your example might look like that:

String dynamicPattern = ...;

ConstraintMapping mapping = new ConstraintMapping();
mapping.type( ContactInfo.class )
    .property( "workPhone", FIELD )
    .constraint( new PatternDef().regexp( dynamicPattern ) );

HibernateValidatorConfiguration config = 
    Validation.byProvider( HibernateValidator.class ).configure();
config.addMapping( mapping );

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