hibernate5 根据xml获取ddl sql语句

发布于:2024-04-27 ⋅ 阅读:(26) ⋅ 点赞:(0)
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

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

    }
}



网站公告

今日签到

点亮在社区的每一天
去签到