Skip to content

BiFunctionUnchecked

BiFunctionUnchecked is a custom @FunctionalInterface designed to handle two-input operations that throw checked exceptions, specifically within database access object (DAO) and business object (BO) patterns^[600-developer-java-java8-java8-lambda01.md]. It allows methods that declare throws SQLException to be used as functional arguments, enabling the extraction of repetitive database logic into reusable templates^[600-developer-java-java8-java8-lambda01.md].

Definition

The interface is annotated with @FunctionalInterface and defines a single abstract method, applyDao, which accepts two parameters and returns a value^[600-developer-java-java8-java8-lambda01.md]. Unlike standard Java functional interfaces (such as BiFunction), this interface permits the underlying implementation to throw a SQLException^[600-developer-java-java8-java8-lambda01.md].

@FunctionalInterface
public interface BiFunctionUnchecked<K, T, V> {
    V applyDao(K k, T t) throws SQLException;
}

Usage

The primary use case for BiFunctionUnchecked is to abstract "boilerplate" resource management code, such as acquiring and closing database connections^[600-developer-java-java8-java8-lambda01.md]. By implementing a generic template method (e.g., in a DefaultBO class), the connection lifecycle—handling try, finally, and transaction management—can be separated from the specific SQL execution logic^[600-developer-java-java8-java8-lambda01.md].

When using this pattern, the specific DAO method (e.g., BeanDao::currentSql) is passed as an argument to the template method^[600-developer-java-java8-java8-lambda01.md].

Operations

Templates utilizing BiFunctionUnchecked typically implement two primary operation modes^[600-developer-java-java8-java8-lambda01.md]:

  • Read Operations: These methods acquire a read-only connection, execute the BiFunctionUnchecked logic, and ensure the connection is closed in a finally block^[600-developer-java-java8-java8-lambda01.md].
  • Write Operations: These methods acquire a write connection, disable auto-commit, execute the function, and explicitly commit the transaction. If an exception occurs, they perform a rollback before re-throwing the exception^[600-developer-java-java8-java8-lambda01.md].

Sources

  • 600-developer-java-java8-java8-lambda01.md