hibernate5 根据xml获取ddl sql语句

java 复制代码
package com.kongjs.kda;

import lombok.val;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.dialect.Dialect;
//import org.hibernate.relational.SchemaManager;
//import org.hibernate.relational.internal.SchemaManagerImpl;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;

import java.util.EnumSet;

public class HibernateCoreTest {
    public static void main1(String[] args) {
        //ServiceRegistry standardRegistry =
        //        new StandardServiceRegistryBuilder().build();

        //MetadataSources sources = new MetadataSources(standardRegistry);

// alternatively, we can build the MetadataSources without passing
// a service registry, in which case it will build a default
// BootstrapServiceRegistry to use.  But the approach shown
// above is preferred
// MetadataSources sources = new MetadataSources();

// add a class using JPA/Hibernate annotations for mapping
        ///sources.addAnnotatedClass(MyEntity.class);

// add the name of a class using JPA/Hibernate annotations for mapping.
// differs from above in that accessing the Class is deferred which is
// important if using runtime bytecode-enhancement
        //sources.addAnnotatedClassName("org.hibernate.example.Customer");

// Read package-level metadata.
        //sources.addPackage("hibernate.example");

// Read package-level metadata.
        //sources.addPackage(MyEntity.class.getPackage());

// Adds the named hbm.xml resource as a source: which performs the
// classpath lookup and parses the XML
        //sources.addResource("org/hibernate/example/Order.hbm.xml");

// Adds the named JPA orm.xml resource as a source: which performs the
// classpath lookup and parses the XML
        //sources.addResource("org/hibernate/example/Product.orm.xml");

// Read all mapping documents from a directory tree.
// Assumes that any file named *.hbm.xml is a mapping document.
        //sources.addDirectory(new File("."));

// Read mappings from a particular XML file
        //sources.addFile(new File("./mapping.xml"));

// Read all mappings from a jar file.
// Assumes that any file named *.hbm.xml is a mapping document.
        //sources.addJar(new File("./entities.jar"));
    }

    public static void main(String[] args) {
        //ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build();

        //MetadataSources sources = new MetadataSources(standardRegistry);

        //MetadataBuilder metadataBuilder = sources.getMetadataBuilder();

// Use the JPA-compliant implicit naming strategy
       // metadataBuilder.applyImplicitNamingStrategy(
        //        ImplicitNamingStrategyJpaCompliantImpl.INSTANCE);

// specify the schema name to use for tables, etc when none is explicitly specified
//        metadataBuilder.applyImplicitSchemaName("my_default_schema");

// specify a custom Attribute Converter
//        metadataBuilder.applyAttributeConverter(myAttributeConverter);

   //     Metadata metadata = metadataBuilder.build();


        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .configure("org/hibernate/example/hibernate.cfg.xml")
                .build();

        Metadata metadata = new MetadataSources(standardRegistry)
                //.addAnnotatedClass(MyEntity.class)
                //.addAnnotatedClassName("org.hibernate.example.Customer")
                .addResource("org/hibernate/example/Order.hbm.xml")
                //.addResource("org/hibernate/example/Product.orm.xml")
                .getMetadataBuilder()
                //.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
                .build();

        //SchemaManager schemaManager = new SchemaManagerImpl();
        SchemaExport schemaExport = new SchemaExport();
        schemaExport.create(EnumSet.of(TargetType.SCRIPT),null);
//        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
//        MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( serviceRegistry ).buildMetadata();
//        SchemaExport schemaExport =  new SchemaExport(metadata);
//        schemaExport.create(true, true);
        //SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
                //.applyBeanManager()
        //        .build();
    }
}

根据以上查看源码后,发现实现可以这样写

仅改一改参数就可以迁移hibernate6

java 复制代码
package com.kongjs.kda;

import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.tool.schema.SourceType;
import org.hibernate.tool.schema.TargetType;
import org.hibernate.tool.schema.internal.ExceptionHandlerCollectingImpl;
import org.hibernate.tool.schema.internal.ExceptionHandlerHaltImpl;
import org.hibernate.tool.schema.spi.*;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

public class HibernateDDL {
    public static SourceDescriptor sourceDescriptor = new SourceDescriptor() {
        public SourceType getSourceType() {
            return SourceType.METADATA;
        }

        public ScriptSourceInput getScriptSourceInput() {
            return null;
        }
    };
    public static void main(String[] args) {
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .configure("org/hibernate/example/hibernate.cfg.xml")
                .build();
        TargetDescriptor targetDescriptor = new TargetDescriptor() {
            @Override
            public EnumSet<TargetType> getTargetTypes() {
                return null;
            }

            @Override
            public ScriptTargetOutput getScriptTargetOutput() {
                return null;
            }
        };
        Map config = new HashMap(serviceRegistry.getService(ConfigurationService.class).getSettings());
        //config.put("hibernate.hbm2ddl.delimiter", this.delimiter);
        //config.put("hibernate.format_sql", this.format);
        //config.put("hibernate.hbm2ddl.import_files", this.importFiles);
        SchemaManagementTool tool = serviceRegistry.getService(SchemaManagementTool.class);
        ExceptionHandler exceptionHandler = true ? ExceptionHandlerHaltImpl.INSTANCE : new ExceptionHandlerCollectingImpl();
        ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions(config, (ExceptionHandler)exceptionHandler);
        SourceDescriptor sourceDescriptor = new SourceDescriptor() {
            public SourceType getSourceType() {
                return SourceType.METADATA;
            }

            public ScriptSourceInput getScriptSourceInput() {
                return null;
            }
        };
        Metadata metadata = new MetadataSources(serviceRegistry)
                //.addAnnotatedClass(MyEntity.class)
                //.addAnnotatedClassName("org.hibernate.example.Customer")
                .addResource("org/hibernate/example/Order.hbm.xml")
                //.addResource("org/hibernate/example/Product.orm.xml")
                .getMetadataBuilder()
                //.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
                .build();

        tool.getSchemaDropper(config).doDrop(metadata, executionOptions, sourceDescriptor, targetDescriptor);

        //tool.getSchemaCreator(config).doCreation(metadata, executionOptions, ContributableMatcher.NONE,sourceDescriptor, targetDescriptor);

    }
}
相关推荐
drebander7 分钟前
使用 Java Stream 优雅实现List 转化为Map<key,Map<key,value>>
java·python·list
乌啼霜满天24911 分钟前
Spring 与 Spring MVC 与 Spring Boot三者之间的区别与联系
java·spring boot·spring·mvc
tangliang_cn16 分钟前
java入门 自定义springboot starter
java·开发语言·spring boot
莫叫石榴姐16 分钟前
数据科学与SQL:组距分组分析 | 区间分布问题
大数据·人工智能·sql·深度学习·算法·机器学习·数据挖掘
程序猿阿伟17 分钟前
《智能指针频繁创建销毁:程序性能的“隐形杀手”》
java·开发语言·前端
找藉口是失败者的习惯23 分钟前
从传统到未来:Android XML布局 与 Jetpack Compose的全面对比
android·xml
Grey_fantasy26 分钟前
高级编程之结构化代码
java·spring boot·spring cloud
弗锐土豆33 分钟前
工业生产安全-安全帽第二篇-用java语言看看opencv实现的目标检测使用过程
java·opencv·安全·检测·面部
Elaine20239134 分钟前
零碎04 MybatisPlus自定义模版生成代码
java·spring·mybatis
小小大侠客1 小时前
IText创建加盖公章的pdf文件并生成压缩文件
java·pdf·itext