Tutorials     About     RSS
Tech and Media Labs

Butterfly Persistence Connection Management

Jakob Jenkov
Last update: 2021-06-30

In this tutorial we will have a look at how Butterfly Persistence is able to manage connections, meaning how either you, or Butterfly Persistence opens connections to a relational database. This is what I refer to as Butterfly Persistence connection management.

Connection Opening Strategies

Your connection management strategy determines how Butterfly Persistence obtains a database connections. You can either let Butterfly Persistence open connections, or open them manually and pass them on to Butterfly Persistence. This text will show how to do both plus discuss a few more issues and features related to connection management. Here is a list of the topics covered:

  1. Automatic Connection Opening
  2. Manual Connection Opening
  3. Full Access to Connection

Automatic Connection Opening

If you want Butterfly Persistence to manage the opening of connections, pass a javax.sql.DataSource implementation into the constructor of the PersistenceManager. Here is how that looks:

public static final PersistenceManager persistenceManager =
    new PersistenceManager(dataSource);

Now, when you create an IDaos instance it will automatically be provided with a connection obtained from the DataSource passed to the PersistenceManager. Here is how creating an IDaos instance looks using automatic connection management:

IDaos daos = persistenceManager.createDaos();

SimpleDataSource

Butterfly Persistence comes with a simple implementation of the DataSource interface if you should need it. It's called

com.jenkov.db.jdbc.SimpleDataSource

Here is how to use it:

DataSource dataSource = new SimpleDataSource(
        "driverName", "dbUrl", "user", "password");

PersistenceManager persistenceManager =
        new PersistenceManager(dataSource);

Manual Connection Opening

It is possible to manage the opening of connections yourself. All you have to do is pass the open connection to the PersistenceManager when creating the IDaos instance. You can do this even if the PersistenceManager has a DataSource set. Here is how it looks:

IDaos daos = persistenceManager.createDaos(connection);

When calling the createDaos(connection) method the PersistenceManager will use the given connection rather than trying to obtain it from its DataSource. This method will also work if the PersistenceManager has no DataSource set.


Full Access to Connection

You can always access the connection from the IDaos instance. Here is how:

Connection connection = daos.getConnection();

Jakob Jenkov

Featured Videos





















Sponsored Ads

Maildroppa - Smart Email Marketing Solution
Close TOC

All Trails

Trail TOC

Page TOC

Previous

Next