louis xie
louis xie

Reputation: 1422

Hibernate-SQLite Dump and Import via Java

How can I make use of Hibernate to perform a backup on my sqlite database? The output should ideally be in the form of an SQL script, similar to the .dump sqlite utility.

Also, to perform a restore of the sql script programmatically as well.

Upvotes: 3

Views: 2011

Answers (3)

Java Man
Java Man

Reputation: 1860

For Unix Flavor cmd not working so used this 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();
    } 

Upvotes: 0

louis xie
louis xie

Reputation: 1422

I have found an alternative to do this, and it is by invoking the sqlite3 command line shell via Java. Here's 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();
    }
  }
}

Upvotes: 2

travega
travega

Reputation: 8415

To my knowledge there is no mechanism in Java to do an SQL dump. But you could create a program to do it quite easily by:

  1. Iterating through a list of your entities - built up using reflection perhaps.
  2. Get you list of column names using JDBC direct (cant really do it with hibernate).
  3. Then creating a select query you pass the Entity name into as a parameter.
  4. Iterate over the result set and push the data via a formatted string to a file.

You can of course add in a DROP IF EXISTS before each CREATE if required.

Upvotes: 0

Related Questions