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包:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天草二十六_简村人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值