-
Notifications
You must be signed in to change notification settings - Fork 22
Get started guide
This guide shows how to get started with FluentJdbc
Java 8
<dependency>
<groupId>org.codejargon</groupId>
<artifactId>fluentjdbc</artifactId>
<version>1.7</version>
</dependency>
A FluentJdbc instance provides Query instances. The following example shows instantiation and configuring a JDBC DataSource.
DataSource dataSource = ...
FluentJdbc fluentJdbc = new FluentJdbcBuilder()
.connectionProvider(dataSource)
// optionally other configuration
.build();
Note: FluentJdbc is thread-safe, generally one instance is enough for an application. There are other ways of providing jdbc Connections to FluentJdbc. See further details at the Integration / ConnectionProvider section in wiki the sidebar. ####Create a Query API instance#### Based on the ConnectionProvider configured for FluentJdbc:
Query query = fluentJdbc.query();
Or alternatively based on a given Connection instance:
Connection connection = ...
Query query = fluentJdbc.queryOn(connection);
The Query interface can then be used to execute any number of SQL queries. ###Querying### Some examples:
Check Insert / Update page for detailed usage instructions. Some examples:
Using positional parameters
UpdateResult result = query
.update("UPDATE CUSTOMER SET NAME = ?, ADDRESS = ?")
.params("John Doe", "Dallas")
.run();
Using named parameters
query
.update("UPDATE CUSTOMER SET NAME = :name, ADDRESS = :address")
.namedParam("name", "John Doe")
.namedParam("address", "Dallas")
.run();
Note: parameter values can be provided as a map
Check the Select page for detailed usage details on select querying and result mapping. Some examples:
List<Customer> customer = query
.select("SELECT * FROM CUSTOMER WHERE NAME = ?")
.params("John Doe")
.listResult(resultSet -> new Customer(resultSet.getString("NAME")));
Optional<Customer> firstCustomer = query
.select("SELECT * FROM CUSTOMER WHERE NAME = ?")
.params("John Doe")
.firstResult(customerMapper);
Map<String, Object> namedParams = ...
Long count = query
.select("SELECT COUNT(*) FROM CUSTOMER WHERE NAME = :name")
.namedParams(namedParams)
.singleResult(Mappers.singleLong());
query
.select("SELECT * FROM CUSTOMER")
.iterateResult(rs -> {
// do something with the customer
});
Check Batch page for more usage details. Some examples:
With positional parameters:
Stream<List<Object>> params = ...;
query
.batch("INSERT INTO CUSTOMER(NAME, ADDRESS) VALUES(?, ?)")
.params(params)
.run();
With named parameters:
Stream<Map<String, Object>> params = ...;
query
.batch("INSERT INTO CUSTOMER(NAME, ADDRESS) VALUES(:name, :address)")
.namedParams(params)
.run();
// Note: iterators are also accepted
Parameters can be normal JDBC types (Integer, Long, String, BigDecimal, java.sql.Date, ...) or java.time types - supported out of the box.
query
.update("UPDATE CUSTOMER SET DEADLINE = ?, UPDATED = ?")
.params(LocalDate.of(2015, Month.MARCH, 5), Instant.now())
.run();
Support for custom types can be configured. See Query parameter types page for more details
Optional<LocalData> deadline = ...
query.update("UPDATE CUSTOMER SET DEADLINE = ?")
.params(deadline)
.run();
UpdateResultGenKeys<Long> result = query
.update("INSERT INTO CUSTOMER(NAME) VALUES(:name)")
.namedParams(namedParams)
.runFetchGenKeys(Mappers.singleLong());
Long id = result.generatedKeys().get(0);
query.transaction().in(
() -> {
query
.update("UPDATE CUSTOMER SET NAME = ?, ADDRESS = ?")
.params("John Doe", "Dallas")
.run();
someOtherBusinessOperationAlsoNeedingTransactions();
}
)
All queries executed in the block will be part of the transaction - in the same thread, based on the same FluentJdbc/ConnectionProvider. Exceptions cause rollback. It is possible to use multiple transactions/datasources simultaneously.
Transaction may be managed outside FluentJdbc, when its based on a transaction-aware datasource
A listener provides a callback mechanism called on each FluentJdbc query operation. This allows things like SQL statement logging, performance measurement. The following example logs all successful SQL operations along with the time taken to execute them:
AfterQueryListener listener = execution -> {
if(execution.success()) {
log.debug(
String.format(
"Query took %s ms to execute: %s",
execution.executionTimeMs(),
execution.sql()
)
)
}
};
FluentJdbc fluentJdbc = new FluentJdbcBuilder()
// other configuration
.afterQueryListener(listener)
.build();
// run queries