0

I'm storing it in a public static field

public class DB {

    private static final String url = "jdbc:sqlite:file:target/todo";
    public static final DBI dbi = new DBI(url);


    public static void migrate() {
        Flyway flyway = new Flyway();
        flyway.setDataSource(url, "", "");
        flyway.migrate();
    }
}

And never close it, is there a better option?

4

2 回答 2

1

This amounts to how you handle getting ahold of any dependency in your application. The best general model, IMHO, is passing it in to the constructor of things that need it. If you want to put some kind of DAO facade around your database access, pass the DBI to the ctor of your DAO. If you are using a DI framework, bind the DBI instance to the framework, and @Inject it.

For your specific question about Connections, the DBI equivalent of a JDBC Connection is the Handle. You should obtain a Handle, use it, and close it as soon as you are done. Typical use of DBI instance is to give it a DataSource which manages actual database connections, by releasing the Handle as soon as you finish with it, you make better use of the connection pool.

In most cases, you would only close the DBI instance if you want to close the Datasource, that is all that closing the DBI instance does. 98% of the time, in a java-for-server world, closing the datasource doesn't make sense, so worrying about closing the DBI (as compared to the Handle) is not a big deal.

When using JDBI, keep in mind:

DBI -> Datasource
Handle -> Connection
Query/SQLStatement -> Statement

This doc elaborates on these.

于 2015-02-26T18:25:17.067 回答
0

The best option is to make a handler class. This class "hands" out handles as someone needs them. You need to worry most about closing the handles. If you really want a fast system, something like c3p0 is great. Normally, it is best to make mutable objects private and final, using getters/setters. You can keep DBI static if you want. When you make a call to checkout a Handle, you should use try-with-resources.

public Handle getHandle(){
    dbi.open(dataSource);
}

public void doSomething(){
    try(Handle handle = getHandle()){
        // Do something
    }
    catch(DBIException e){
        // TODO Handle it...
    }
}

I'd probably make my handler autocloseable and close everything left over (like any connection pools) when it closes. This, by the way, lets you pull your credentials in the handler and keep that data safe there.

于 2015-02-25T13:00:19.423 回答