Skip to content

fabriciofx/cactoos-jdbc

Repository files navigation

winner

EO principles respected here We recommend IntelliJ IDEA Java Profiler

Maven Central Javadoc License

Hits-of-Code

Introduction

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.

Features

  • Select, Insert, Update and Delete data from a RDBMS
  • Named parameters statement
  • Retrieve the data as XML
  • Easy logging
  • SQL Script execution
  • Batch
  • Transactions
  • Pagination

Feature to be implemented

  • Tests on PostgreSQL and MySQL RDBMS (done)
  • Retrieve the data as JSON
  • Caching
  • Call Store Procedures

How to use

<dependency>
  <groupId>com.github.fabriciofx</groupId>
  <artifactId>cactoos-jdbc</artifactId>
</dependency>

Java version required: 1.8+.

Usage

Let's show how use the API. For all above examples, let's start creating a Session object:

final Session session = new NoAuth(
    new H2Source("testdb")
);

Update

Now, let's create a table using a Update command:

new Update(
    session,
    new QueryOf(
        new Joined(
            " ",
            "CREATE TABLE employee (id INT AUTO_INCREMENT,"
            "name VARCHAR(50), salary DOUBLE)"
        )
    )
).result()

Insert

Let's insert a new employee and return the id of inserted employee.

final int id = new ResultAsValue<Integer>(
    new InsertWithKey(
        session,
        new QueryWithKey(
            () -> "INSERT INTO employee (name, salary) VALUES (:name, :salary)",
            "id",
            new TextOf("name", "Jeff Bridge"),
            new DoubleOf("salary", 12345.00)
        )
    )
).value();

Select

Let's retrieve the name of a employee:

final String name = new ResultAsValue<String>(
    new Select(
        session,
        new QueryOf(
            "SELECT name FROM employee WHERE id = :id",
            new IntOf("id", 123)
        )
    )
).value();

Let's retrieve all employee salaries:

final List<Double> salaries = new ResultAsValues<Double>(
    new Select(
        session,
        new QueryOf("SELECT salary FROM employee")
    )
).value();

Transaction

To enable a transaction you will need to do two things:

  1. Decorates a Session using a Transacted object, like here:
final Session transacted = new Transacted(session);
  1. Use a Transaction object to perform all transacted operations, like here:
new Transaction(
  transacted,
  () -> {
    final Contact contact = new ContactsSql(transacted)
        .contact("Albert Einstein");
    contact.phones().phone("912232325", "TIM");
    contact.phones().phone("982231234", "Oi");
    return contact;
  }
).result();

To a complete example, please take a look here.

Pagination

To enable pagination, you need define a method which should return Pages<> of ah object, like this:

public interface Phonebook {
    ...
    Pages<Contact> contacts(int max) throws Exception;
}

And in this method, we need create a SqlPages<> object, that must contains three objects:

  1. A QueryOf that must return the amount of registers;
  2. A QueryOf that must return all registers (don't worry: pagination will not retrieve all registers. They will be paginated);
  3. An Adapter that will transform a ResulSet in an object.

We can see an example bellow:

public final class SqlPhonebook implements Phonebook {
    ...
    @Override
    public Pages<Contact> contacts(final int max) throws Exception {
        return new SqlPages<>(
            this.session,
            new QueryOf("SELECT COUNT(*) FROM contact"),
            new QueryOf("SELECT * FROM contact"),
            new ResulSetAsContact(this.session),
            max
        );
    }
}

To see more details, please take a look here.

Logging

To enable logging just decorate a Session object:

final Session logged = new Logged(session);

Phonebook application (demo)

A phonebook application has been developed to demonstrate and test the catoos-jdbc API. To see it, please look here.

Contributions

Contributions are welcome! Please, open an issue before submit any kind (ideas, documentation, code, ...) of contribution.

How compile it?

$ mvn clean install -Pqulice

License

The MIT License (MIT)

Copyright (C) 2018-2023 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.

Acknowledgements

David West (Blog) for:

@yegor256 as Yegor Bugayenko (Blog) for:

@mdbs99 as Marcos Douglas B. Santos (Blog) @paulodamaso as Paulo Lobo for:

  • OOP suggestions and discussion