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);

    }
}
相关推荐
测开小菜鸟几秒前
使用python向钉钉群聊发送消息
java·python·钉钉
P.H. Infinity1 小时前
【RabbitMQ】04-发送者可靠性
java·rabbitmq·java-rabbitmq
生命几十年3万天1 小时前
java的threadlocal为何内存泄漏
java
caridle1 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
^velpro^1 小时前
数据库连接池的创建
java·开发语言·数据库
苹果醋31 小时前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx
秋の花1 小时前
【JAVA基础】Java集合基础
java·开发语言·windows
小松学前端1 小时前
第六章 7.0 LinkList
java·开发语言·网络
Wx-bishekaifayuan2 小时前
django电商易购系统-计算机设计毕业源码61059
java·spring boot·spring·spring cloud·django·sqlite·guava
customer082 小时前
【开源免费】基于SpringBoot+Vue.JS周边产品销售网站(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·java-ee·开源