0

I am developing a JPA application which uses H2 for the database. I want to create a backup (export as sql file) and import a backup from a webinterface.

The creation of the backup sql file and the upload of the sql file is working but I can't get the entityManager to properly execute the imported sql file.

I tried creating a file from the imported sql and then running it as follows:

public void applyBackup() {
    em.flush();
    Query query = em.createNativeQuery("DROP ALL OBJECTS");
    query.executeUpdate();

    query = em.createNativeQuery("RUNSCRIPT FROM 'backup.sql'");
    query.executeUpdate();
}

The problem here is, that the file I created from the imported sql is located in the server folder, while the RUNSCRIPT query tries to run it from the project folder.

My second attempt is parse the sql into a string and then executing this as a sql command:

  public void applyBackup(String sqlStr) {
    em.flush();
    Query query = em.createNativeQuery("DROP ALL OBJECTS");
    query.executeUpdate();

    query = em.createNativeQuery(sqlStr);
    query.executeUpdate();
}

This doesn't throw an exeception during execution but when I try to get data out of the database, it says that table xy is not found.

To create the backup I use the following query:

  Query query = em.createNativeQuery("SCRIPT TO 'backup.sql'");

As described here.

6
  • seems like you put the same code for importing sql and parsing it to string by mistake. Commented Feb 28, 2020 at 14:21
  • also it seems a duplicate of stackoverflow.com/questions/14358425/… Commented Feb 28, 2020 at 14:24
  • I edited my post. The solution in your suggested duplicate raises an SQLGrammarException. Commented Feb 28, 2020 at 14:38
  • If you have your backup as a File, you could try: RUNSCRIPT FROM ' + file.getAbsolutePath() + '? Commented Feb 28, 2020 at 15:35
  • The file is found using the absolute path but when trying to load the data from the database it says that table .. is not found. Interestingly the backup.sql in my resources folder, which is created automatically during the "SCRIPT TO" query works. The problem is, that I dont know how I can create an sql-file in my resources folder from the imported file and I also don't know if this is a viable solution when using the war file to run the program. Commented Feb 28, 2020 at 16:05

1 Answer 1

0

I parsed the UploadedFile file's InputStream with a Scanner, which messed up the SQL.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.