[英]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: 这里要注意的事情:
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.