java持久化框架JPA,自动执行sql语句的代码实现

在springboot入口处调用:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class XxxServerBootstrap implements CommandLineRunner {

    @Autowired
    private SchemaExecutor schemaExecutor;

    @Override
    public void run(String... strings) throws Exception {
        schemaExecutor.execute();
    }

    public static void main(String[] args) {
        SpringApplication.run(XxxServerBootstrap.class, args);
    }
}

具体实现参考:

import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Component
public class SchemaExecutor {
    private final Logger logger = LoggerFactory.getLogger(SchemaExecutor.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional(rollbackOn = Exception.class)
    public void execute() {
        List<String> lines = readScripts();

        for (String line : lines) {
            Query query = entityManager.createNativeQuery(line);
            int row = query.executeUpdate();
            logger.info("execute {} return row {}", line, row);
        }
    }

    private List<String> readScripts() {
        List<String> lines = new ArrayList<>(0);

        try {
            File[] files = new File(getRuntimePath()).listFiles((pathname) -> pathname.getName().endsWith(".sql"));

            for (File file : files) {
                lines.addAll(Files.readLines(file, Charset.defaultCharset()));
                file.delete();
            }

            return lines;
        } catch (IOException e) {
            logger.info("not found file schema.sql");
            return lines;
        }
    }

    private String getRuntimePath() {
        String locationPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        File runtimePath;

        try {
            locationPath = URLDecoder.decode(locationPath, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }

        File locationFile = new File(locationPath);
        runtimePath = matchParent(locationFile, ".jar!");

        if (runtimePath == null) {
            runtimePath = matchParent(locationFile, "classes");
        } else {
            runtimePath = runtimePath.getParentFile();
        }

        if (runtimePath == null) {
            throw new RuntimeException("not find current program runtime path");
        }

        return URI.create(runtimePath.getPath()).getPath();
    }

    private File matchParent(File file, String name) {
        File parent = file;

        while (parent != null) {
            if (parent.getAbsolutePath().endsWith(name)) {
                return parent;
            }
            parent = parent.getParentFile();
        }

        return null;
    }
}

依赖的jar包:

java持久化框架JPA,自动执行sql语句的代码实现_第1张图片

你可能感兴趣的:(java,spring,boot)