简体   繁体   English

JPA实体管理器 - 如何运行SQL脚本文件?

[英]JPA Entity Manager - How to run SQL script file?

I have an SQL script file which drops and recreates various tables as well as inserts various records into these tables. 我有一个SQL脚本文件,它删除并重新创建各种表,并在这些表中插入各种记录。 The script runs fine when executing in the SQL query console however I need it to be executed by the Entity Manager. 在SQL查询控制台中执行时脚本运行正常但是我需要它由实体管理器执行。

Any idea's on how I would be able to do this? 我有什么想法可以做到这一点?

Thanks, 谢谢,

H H

Late to the party but here's how I do it. 迟到了,但这就是我的方式。 Couple of things to note here: 这里要注意的事情:

  • My SQL file ("sql-queries.sql") is on the classpath - you could do this any other way that will get you an input stream... 我的SQL文件(“sql-queries.sql”)在类路径上 - 您可以通过任何其他方式执行此操作,以获取输入流...
  • My SQL file has 1 statement per line 我的SQL文件每行有1个语句
  • I'm manually beginning/committing transactions, one for each line/statement in the file 我手动开始/提交事务,一个用于文件中的每一行/语句

Here's the method to execute the file: 这是执行文件的方法:

void executeStatements(BufferedReader br, EntityManager entityManager) throws IOException {
    String line;
    while( (line = br.readLine()) != null )
    {
        entityManager.getTransaction().begin();
        entityManager.createNativeQuery(line).executeUpdate();
        entityManager.getTransaction().commit();
    }
}

Here's how I call it: 这是我如何称呼它:

        InputStream sqlFileInputStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("geo-data.sql");

        // Convert input stream to something that can be read line-by-line

        BufferedReader sqlFileBufferedReader = new BufferedReader( new InputStreamReader(sqlFileInputStream));
        executeStatements(sqlFileBufferedReader, dao.getEntityManager());

I tested nominally with 1 transaction instead of 1 per statement (note that this means that 1 bad query will break everything) and the time to execute is the same: 我名义上用1个事务测试而不是每个语句1个(请注意,这意味着1个错误的查询会破坏所有内容)并且执行的时间是相同的:

void executeStatements(BufferedReader br, EntityManager entityManager) throws IOException {
    String line;
    entityManager.getTransaction().begin();
    while( (line = br.readLine()) != null )
    {
        entityManager.createNativeQuery(line).executeUpdate();
    }
    entityManager.getTransaction().commit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM