我发现以下方法可以在 Hibernate 5.1 的模式导出期间实现对验证器属性的评估。
添加一个新的类CustomMetadataContributor:
package de.test;
import org.hibernate.MappingException;
import org.hibernate.boot.internal.ClassLoaderAccessImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.spi.ClassLoaderAccess;
import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataContributor;
import org.hibernate.cfg.SecondPass;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.jboss.jandex.IndexView;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
public class CustomMetadataContributor implements MetadataContributor {
public void contribute(InFlightMetadataCollector metadataCollector, IndexView jandexIndex){
metadataCollector.addSecondPass(new SecondPass() {
@Override
public void doSecondPass(final Map persistentClasses) throws MappingException {
try {
Method applyDDL = Class.forName("org.hibernate.cfg.beanvalidation.TypeSafeActivator") //
.getMethod("applyRelationalConstraints", ValidatorFactory.class, Collection.class, Map.class, Dialect.class, ClassLoaderAccess.class);
applyDDL.setAccessible(true);
StandardServiceRegistry serviceRegistry = metadataCollector.getMetadataBuildingOptions().getServiceRegistry();
applyDDL.invoke(null, Validation.buildDefaultValidatorFactory() ,metadataCollector.getEntityBindings(), serviceRegistry.getService( ConfigurationService.class ).getSettings(), serviceRegistry.getService( JdbcServices.class ).getDialect(),new ClassLoaderAccessImpl(serviceRegistry.getService( ClassLoaderService.class )));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
}
此外,您需要在路径中添加一个文本文件(没有文件扩展名)
META-INF/services/org.hibernate.boot.spi.MetadataContributor
包含
de.test.CustomMetadataContributor
而de.test需要替换为您的包名称。