javapersistencederbyjdb

Cannot close derby connection with EntityManagerFactory


I need to compress a database inside a zip file after it's been created (and delete the original version of the database). After creating it using EntityManagerFactory I close it so that the connection is freed and I can manipulate the database file.

The problem is that even if I close the EntityManagerFactory the database directory is still blocked because it says it is in use (it shouldn't?).

I created a mre recreating the problem...

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {

    private static EntityManagerFactory entityManagerFactory;

    public static void main(String[] args) {
        String dbURL = "jdbc:derby:C:\\Users\\XXX\\Desktop\\MyDB;create=true";

        Map<String, String> persistenceMap = new HashMap<String, String>();
        persistenceMap.put("javax.persistence.jdbc.url", dbURL);
    
        entityManagerFactory = Persistence.createEntityManagerFactory("PUBLIC", persistenceMap);        
        entityManagerFactory.close();
        entityManagerFactory = null;
    
        System.out.println("DONE");

        //I should be able to delete the database directory now (I'm not).
    
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Solution

  • Problem solved, I had to shutdown the database.

    try {
            DriverManager.getConnection(
                    "jdbc:derby:" + TEMP + "/" + projectName + ";user=xxxx;password=xxxx;shutdown=true");
        } catch (SQLException sqle) {
            //If catches exception went well
        }