Class SQLManager
Generic SQL connection manager with HikariCP connection pooling.
This class provides a complete solution for managing database connections in plugins, including connection pooling, configuration reloads, reconnection handling, and table creation/migration support.
Features
- Connection Pooling: Uses HikariCP for efficient connection management
- Config Reloads: Supports hot-reloading database configuration
- Auto-Reconnect: Automatically attempts to reconnect on connection loss
- Table Management: Built-in support for table creation and migrations
- Thread Safety: All operations are thread-safe
Example Usage with PooledDatabaseConfig (Recommended)
// Using MariaDbConfig from commons-database-mariadb
MariaDbConfig dbConfig = config.database();
SQLManager sqlManager = SQLManager.create(dbConfig)
.poolName("MyPlugin-Pool")
.logger(plugin.getLogger())
.build();
// Register tables to create on connect
sqlManager.registerTable("""
CREATE TABLE IF NOT EXISTS players (
uuid VARCHAR(36) PRIMARY KEY,
name VARCHAR(16) NOT NULL
)
""");
// Connect and create tables
sqlManager.connect();
// Use connections safely with callbacks
sqlManager.withConnection(connection -> {
// Use connection safely
});
// Shutdown when done
sqlManager.shutdown();
Using Withers for Config Overrides
// Create a modified config for a specific use case
MariaDbConfig authMeConfig = config.database()
.withDatabase("authme")
.withMaxPoolSize(5);
SQLManager authMeManager = SQLManager.create(authMeConfig)
.poolName("AuthMe-Pool")
.build();
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classBuilder for creating SQLManager instances.static interfaceFunctional interface for connection consumers that may throw SQLException.static interfaceFunctional interface for connection functions that may throw SQLException. -
Method Summary
Modifier and TypeMethodDescriptionvoidconnect()Connects to the database and initializes the connection pool.static SQLManager.Buildercreate(PooledDatabaseConfig config) Creates a new builder for SQLManager using a pooled database configuration.@Nullable ConnectionGets a connection from the pool.Gets the current database credentials.booleanChecks if the manager is currently connected to the database.voidAttempts to reconnect to the database.voidregisterMigration(int version, String description, String sql) Registers a database migration.voidregisterTable(String createTableSql) Registers a table creation SQL statement.voidreload(DatabaseCredentials newCredentials) Reloads the database configuration and reconnects.voidshutdown()Shuts down the connection pool.booleanExecutes an action with a database connection.<T> @Nullable TExecutes an action with a database connection and returns a result.
-
Method Details
-
create
Creates a new builder for SQLManager using a pooled database configuration.
This is the recommended way to create an SQLManager. The configuration provides credentials, pool size, and idle connection settings.
- Parameters:
config- the pooled database configuration- Returns:
- a new builder instance with config applied
-
connect
public void connect()Connects to the database and initializes the connection pool.
This method will create the HikariCP connection pool using the current configuration. If already connected, this method does nothing.
After connecting, all registered table creation statements and migrations will be executed.
-
getConnection
Gets a connection from the pool.
This method returns null instead of throwing an exception when unable to get a connection. This allows for easier error handling in calling code.
Important: The returned connection must be closed after use. Use try-with-resources for automatic cleanup.
- Returns:
- a database connection, or null if unavailable
-
withConnection
Executes an action with a database connection.
This is a convenience method that handles connection retrieval and automatic cleanup. The connection is automatically closed after the action completes.
- Parameters:
action- the action to execute with the connection- Returns:
- true if the action executed successfully, false if no connection was available
-
withConnectionResult
Executes an action with a database connection and returns a result.- Type Parameters:
T- the type of result- Parameters:
action- the action to execute with the connection- Returns:
- the result, or null if no connection was available or an error occurred
-
reconnect
public void reconnect()Attempts to reconnect to the database.
This method closes the existing connection pool (if any) and creates a new one with the current configuration.
-
reload
Reloads the database configuration and reconnects.
This method allows hot-reloading of database configuration. The existing connection pool is closed and a new one is created with the new configuration.
- Parameters:
newCredentials- the new database credentials
-
registerTable
-
registerMigration
Registers a database migration.
Migrations are executed in order of their version number when
connect()is called. Each migration runs only once, tracked by a migrations table.- Parameters:
version- the migration version (must be unique and sequential)description- a description of what the migration doessql- the SQL statement(s) to execute
-
shutdown
public void shutdown()Shuts down the connection pool.
This method should be called when the plugin is disabled to properly release database resources.
-
isConnected
public boolean isConnected()Checks if the manager is currently connected to the database.- Returns:
- true if connected, false otherwise
-
getCredentials
Gets the current database credentials.- Returns:
- the current credentials
-