Hibernate-SQLite dump and import via Java

How can I use hibernate to backup in my sqlite database? Ideally, the output should be in the form of an SQL script, similar to the sqlite.dump utility.

In addition, to perform sql recovery script also programmatically.

+1
source share
3 answers

I found an alternative for this, and this is caused by the sqlite3 command line shell through Java. Here is my sample solution

public class Test { public static void main(String args[]) { try { String line; Process p = Runtime.getRuntime().exec("cmd /c start /b sqlite3 db.sqlite .dump > dump.txt"); BufferedReader bri = new BufferedReader (new InputStreamReader(p.getInputStream())); BufferedReader bre = new BufferedReader (new InputStreamReader(p.getErrorStream())); while ((line = bri.readLine()) != null) { System.out.println(line); } bri.close(); while ((line = bre.readLine()) != null) { System.out.println(line); } bre.close(); p.waitFor(); System.out.println("Done."); } catch (Exception err) { err.printStackTrace(); } } } 
+1
source

For Unix Flavor cmd does not work, so it is used for ubuntu.

  try { String line; Runtime rt = Runtime.getRuntime(); Process p = rt.exec(new String[]{"/bin/sh", "-c", "sqlite3 /home/ubuntu/test.sqlite .dump > /home/ubuntu/output.sql"}); BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = bri.readLine()) != null) { System.out.println(line); } bri.close(); while ((line = bre.readLine()) != null) { System.out.println(line); } bre.close(); p.waitFor(); System.out.println("Done."); } catch (Exception err) { err.printStackTrace(); } 
+1
source

As far as I know, in Java there is no mechanism for dumping SQL. But you could create a program to do this quite easily:

  • Iterating through a list of your entities - possibly using reflection.
  • Get a list of column names using JDBC direct (can not really with hibernation).
  • Then, when creating a select query, you pass the name Entity as a parameter.
  • Iterate over a set of results and transfer data through a formatted string to a file.

You can, of course, add DROP IF EXISTS before each CREATE, if necessary.

0
source

Source: https://habr.com/ru/post/1203118/


All Articles