Cactoos-JDBC is a collection of object-oriented Java wrapper classes to JDBC.
Motivation. We are not happy with JDBC because it is procedural and not object-oriented. It does its job, but mostly through strongly coupled classes and static methods. Cactoos JDBC is suggesting to do almost exactly the same, but through (more OO) objects.
Besides, ORM is a anti-pattern and should avoid with all cost. But we can use an library to help us to make our data persistence. Thus, Cactoos JDBC will help us to do it too.
Principles. These are the design principles behind Cactoos JDBC.
- Select, Insert, Update and Delete data from a RDBMS
- Named parameters statement
- Retrieve the data as XML
- Easy logging
- Batch
- Transactions
- Pagination
- Caching
- Connection pooling
- Query timeout and max rows
Tests on PostgreSQL and MySQL RDBMS(done)Caching(done)- Retrieve the data as JSON
- Call Store Procedures
<dependency>
<groupId>com.github.fabriciofx</groupId>
<artifactId>cactoos-jdbc</artifactId>
<version>1.0.2</version>
</dependency>Java version required: 21+.
The API is built around three concepts:
- A
Sourceknows how to reach a database and createsSessions; - A
Sessionwraps a JDBC connection and must be closed after use; - A
Statement(Select,Insert,KeyedInsert,Update,BatchandTransaction) runs aQueryinside aSession.
For all examples below, let's start creating a Source from any
javax.sql.DataSource and opening a Session:
final Source source = new NoAuth(dataSource);
try (Session session = source.session()) {
...
}If you need credentials, use Auth instead:
final Source source = new Auth(dataSource, "user", "secret");Or, if you prefer a JDBC URL, use Driver:
final Source source = new Driver(
"jdbc:postgresql://localhost:5432/db",
"user",
"secret"
);There are two kinds of queries:
QueryOf: a plain SQL query, without parameters;NamedQuery: a SQL query with named parameters (:name), bound byParamobjects likeTextParam,IntParam,LongParam,DoubleParam,DecimalParam,BoolParam,DateParam,DateTimeParam,UuidParam,UuidAsBytesParamandAnyParam.
Let's create a table using an Update statement:
new Update(
session,
new QueryOf(
"""
CREATE TABLE employee (id INT AUTO_INCREMENT, name VARCHAR(50),
salary DECIMAL(20,2), PRIMARY KEY (id))
"""
)
).execute();Update also runs UPDATE and DELETE commands:
new Update(
session,
new NamedQuery(
"DELETE FROM employee WHERE id = :id",
new IntParam("id", 1)
)
).execute();Let's insert a new employee:
new Insert(
session,
new NamedQuery(
"INSERT INTO employee (name, salary) VALUES (:name, :salary)",
new TextParam("name", "Jeff Bridges"),
new DecimalParam("salary", "12345.00")
)
).execute();To insert and get back the generated key, use KeyedInsert:
final int id = new KeyedInsert<Integer>(
session,
new NamedQuery(
"INSERT INTO employee (name, salary) VALUES (:name, :salary)",
new TextParam("name", "Jeff Bridges"),
new DecimalParam("salary", "12345.00")
)
).execute();To insert many records at once, use Batch with one ParamsOf per record:
new Batch(
session,
new NamedQuery(
"INSERT INTO employee (name, salary) VALUES (:name, :salary)",
new ParamsOf(
new TextParam("name", "John Wick"),
new DecimalParam("salary", "13456.00")
),
new ParamsOf(
new TextParam("name", "Adam Park"),
new DecimalParam("salary", "12345.00")
)
)
).execute();A Select returns a java.sql.ResultSet:
try (
ResultSet rset = new Select(
session,
new QueryOf("SELECT salary FROM employee")
).execute()
) {
while (rset.next()) {
...
}
}Let's retrieve the name of an employee using ResultSetAsValue:
final String name = new ResultSetAsValue<String>(
new Select(
session,
new NamedQuery(
"SELECT name FROM employee WHERE id = :id",
new IntParam("id", 1)
)
)
).value();Or retrieve all employees as XML using ResultSetAsXml:
final String xml = new ResultSetAsXml(
new Select(
session,
new QueryOf("SELECT * FROM employee")
),
"employees",
"employee"
).value();To enable a transaction you will need to do two things:
- Decorate a
Sourceusing aTransactedobject, which shares a single non auto-committedSession, like here:
final Source transacted = new Transacted(source);- Use a
Transactionstatement to perform all transacted operations. It commits if everything goes fine, or rolls back if an exception is thrown:
try (Session session = transacted.session()) {
new Transaction<>(
session,
() -> {
final Contact contact = new SqlPhonebook(transacted)
.create("Albert Einstein");
contact.phones().add("99991234", "TIM");
contact.phones().add("98812564", "Oi");
return contact;
}
).execute();
}To a complete example, please take a look in TransactionTest.
To paginate any query, decorate it with Paginated, informing the page number
(starting from 1) and the page size. Besides the query columns, each row
brings the total amount of records in the __total_count__ column:
try (
ResultSet rset = new Select(
session,
new Paginated(
new QueryOf("SELECT * FROM contact"),
1,
10
)
).execute()
) {
...
}To expose pages in your domain, implement Pages<T>, which returns a
Page<T> with its items(), total(), number() and count():
public interface Phonebook extends Pages<Contact> {
...
}
public final class SqlPhonebook implements Phonebook {
...
@Override
public Page<Contact> page(final int number, final int count) {
return new SqlContactPage(this.source, number, count);
}
}To see more details, please take a look in SqlContactPage.
To enable logging just decorate a Source object:
final Source logged = new Logged(source, "app");To cache Select results, decorate a Source with Cached. Any INSERT,
UPDATE, DELETE or MERGE on a table invalidates its cached entries, while
a TRUNCATE, DROP TABLE or ALTER TABLE clears the whole cache:
final Source cached = new Cached(source);The cache has some limitations:
- Transactions: while a session has autocommit disabled, its
Selects bypass the cache and always go to the database, so uncommitted rows are never exposed to other sessions. Acommitinvalidates the cached entries of the tables the transaction changed. - Views: a
Selectthat reads a view is never cached, because writes to the view's underlying tables cannot be tracked. Finding out whether aSelectreads a view requires a query to the database metadata whenever its result is not cached.
To use a connection pool (HikariCP),
decorate a Source with Pooled:
final Source pooled = new Pooled(source);A Session can be decorated to set a query timeout (in seconds) or to limit
the number of retrieved rows:
try (Session session = new Timeout(new MaxRows(source.session(), 100), 5)) {
...
}A phonebook application has been developed to demonstrate and test the Cactoos-JDBC API. To see it, please take a look in phonebook.
Contributions are welcome! Please, open an issue before submit any kind (ideas, documentation, code, ...) of contribution.
mvn clean install -PquliceThe MIT License (MIT)
Copyright (C) 2018-2026 Fabrício Barros Cabral
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
David West (Blog) for:
- Object Thinking Book
@yegor256 as Yegor Bugayenko (Blog) for:
-
Elegant Objects Vol. 1 and Vol. 2 books
-
jcabi-jdbc JDBC wrapper which Cactoos JDBC is based too
@mdbs99 as Marcos Douglas B. Santos (Blog) and @paulodamaso as Paulo Lobo for:
- OOP suggestions and discussion

