Hibernate6根据xml获取ddl sql语句

java 复制代码
package com.kongjs.dbmo.jdbc;

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.ExceptionHandlerHaltImpl;
import org.hibernate.tool.schema.spi.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.*;

public class Hibernate6DDL {

    public static String getDDLSql(String dialect, File dir) {
        StringBuilder sb = new StringBuilder();
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySetting("hibernate.dialect", dialect)
                .applySetting("hibernate.temp.use_jdbc_metadata_defaults", false)
                .build();
        try {
            Metadata metadata = new MetadataSources(serviceRegistry)
                    .addDirectory(dir)
                    .buildMetadata();

            Map<String, Object> config = new HashMap<>(Objects.requireNonNull(serviceRegistry.getService(ConfigurationService.class)).getSettings());
            ExceptionHandler exceptionHandler = ExceptionHandlerHaltImpl.INSTANCE;
            ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions(config, exceptionHandler);
            SchemaManagementTool tool = serviceRegistry.getService(SchemaManagementTool.class);

            SourceDescriptor sourceDescriptor = new SourceDescriptor() {
                @Override
                public SourceType getSourceType() {
                    return SourceType.METADATA;
                }

                @Override
                public ScriptSourceInput getScriptSourceInput() {
                    return null;
                }
            };

            TargetDescriptor targetDescriptor = new TargetDescriptor() {
                @Override
                public EnumSet<TargetType> getTargetTypes() {
                    return EnumSet.of(TargetType.SCRIPT);
                }

                @Override
                public ScriptTargetOutput getScriptTargetOutput() {
                    return new ScriptTargetOutput() {
                        @Override
                        public void prepare() {

                        }

                        @Override
                        public void accept(String command) {
                            sb.append(command);
                            sb.append("\n");
                        }

                        @Override
                        public void release() {

                        }
                    };
                }
            };

            Objects.requireNonNull(tool);

            SchemaCreator schemaCreator = tool.getSchemaCreator(config);
            schemaCreator.doCreation(metadata, executionOptions, ContributableMatcher.ALL, sourceDescriptor, targetDescriptor);

            SchemaDropper schemaDropper = tool.getSchemaDropper(config);
            schemaDropper.doDrop(metadata, executionOptions, ContributableMatcher.ALL, sourceDescriptor, targetDescriptor);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StandardServiceRegistryBuilder.destroy(serviceRegistry);
        }
        return sb.toString();
    }

    public static final Map<String, String> dialects = new LinkedHashMap<>();

    public static void initDialect(String classpath) {
        try {
            ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resourcePatternResolver.getResources(classpath);
            for (Resource resource : resources) {
                String filename = resource.getFilename();
                if (filename == null) {
                    continue;
                }
                if (filename.contains("Dialect") && !filename.contains("Abstract")) {
                    int indexOf = filename.indexOf("Dialect");
                    String name = filename.substring(0, indexOf);
                    if (!StringUtils.hasLength(name)) {
                        continue;
                    }
                    if (!filename.contains("community")) {
                        dialects.put(name, "org.hibernate.dialect." + name + "Dialect");
                    } else {
                        dialects.put(name, "org.hibernate.community.dialect." + name + "Dialect");
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    static {
        String path1 = "classpath*:/org/hibernate/dialect/**";
        //initDialect(path1);
        String path2 = "classpath*:/org/hibernate/community/dialect/**";
        //initDialect(path2);
    }

    public static void main(String[] args) throws FileNotFoundException {
        //System.out.println(dialects);
        //System.out.println(getCreatorSql("org.hibernate.dialect.PostgreSQLDialect",
                //new FileInputStream("C:\\Users\\Administrator\\IdeaProjects\\dbmo\\dbmo-start\\src\\test\\resources\\Event.hbm.xml")));
    }
}
相关推荐
九皇叔叔1 小时前
【7】SQL 语句基础应用
数据库·sql·mysql
麦兜*1 小时前
Spring Boot 集成 Docker 构建与发版完整指南
java·spring boot·后端·spring·docker·系统架构·springcloud
Cisyam^1 小时前
Go环境搭建实战:告别Java环境配置的复杂
java·开发语言·golang
CHENFU_JAVA2 小时前
使用EasyExcel实现Excel单元格保护:自由锁定表头和数据行
java·excel
小云数据库服务专线3 小时前
GaussDB 数据库架构师修炼(十八) SQL执行引擎-概述
sql·数据库架构·gaussdb
青云交3 小时前
Java 大视界 -- 基于 Java 的大数据实时流处理在智能电网分布式电源接入与电力系统稳定性维护中的应用(404)
java·大数据·分布式·智能电网·flink 实时流处理·kafka 数据采集·iec 61850 协议
麦聪聊数据3 小时前
能源行业数据库远程运维安全合规实践:Web化平台的落地经验
运维·数据库·sql·安全·数据服务
仰望星空@脚踏实地4 小时前
maven scope 详解
java·maven·scope
M_Reus_114 小时前
Groovy集合常用简洁语法
java·开发语言·windows
带刺的坐椅4 小时前
10分钟带你体验 Solon 的状态机
java·solon·状态机·statemachine