独立模式导出Hibernate Validator集成

时间:2018-09-05 14:56:10

标签: hibernate ddl schemaexport

如此处所述:

http://devmint.blogspot.com/2013/02/hibernate-schema-export-with-hibernate.html

验证者特定的注释不再被SchemaExport识别。

如何将“ injectBeanValidationConstraintToDdlTranslator”方法转换为Hibernate 5.2?

配置文件不再存在,如下所示:

Where did Configuration.generateSchemaCreationScript() go in Hibernate 5

谢谢。

1 个答案:

答案 0 :(得分:0)

我发现以下方法可以在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 需要用您的软件包名称替换。