DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. JDBI, a Nice Spring JDBC Alternative

JDBI, a Nice Spring JDBC Alternative

If you’re looking into doing plain JDBC work and need something different than JDBC template, have a look at JDBI. Here's how you can use it as a JDBC alternative.

Lieven Doclo user avatar by
Lieven Doclo
·
Sep. 06, 15 · Tutorial
Like (7)
Save
Tweet
Share
25.41K Views

Join the DZone community and get the full member experience.

Join For Free

Recently I was researching some more Java EE-like alternatives for Spring Boot, such as WildFly Swarm and Dropwizard. And while looking at Dropwizard, I noticed they were using a library for JDBC access I hadn’t encountered before: JDBI. Normally, my first response to plain JDBC access is using the JdbcTemplate class Spring provides, but lately I’ve been having some small issues with it (for example it not being able to handle getting the generated keys for a batch insert in an easy way). I’m always interested in giving other solutions a try so I started a small PoC project with JDBI. And I was pleasantly suprised.

JDBI is an abstraction layer on top of JDBC much like JdbcTemplate. And it shares most if not all the functionality JdbcTemplate provides. What’s interesting is what it provides in addition to that. I’ll talk about a couple of them.

Built in Support For Both Named and Indexed Parameters in SQL

Most of you know you have JdbcTemplate and NamedParameterJdbcTemplate. The former supports indexed parameters (using ?) while the latter supports named parameters (using :paramName). JDBI actually has built in support for both and does not need different implementations for both mechanisms. JDBI uses the concept of parameter binding while executing a query and you can bind either to an index or to a name. This makes the API very easy to learn.

Fluent API Functionality

JDBI has a very fluent API. For example, take this simple query with JdbcTemplate:

Map<String, Object> params = new HashMap<>();
params.put("param", "bar");
return jdbcTemplate.queryForObject("SELECT bar FROM foo WHERE bar = :param", params, String.class);

With JDBI, this would result in this (jdbi is an instance of the JDBI class):

Handle handle = jdbi.open();
String result =  handle
    .createQuery("SELECT bar FROM foo WHERE bar = :param")
    .bind("param", "bar")
    .first(String.class);
handle.close();
return result;

To be completely correct, these two methods aren’t really functionally equivalent. The JdbcTemplate version will throw an exception if no result or multiple results are returned whereas the JBDI version will either return null or the first item in the same situation. So to be functionally equivalent, you’d have to add some logic if you want the same behavior, but you get the idea.

Also be aware you need to close your Handle instance after you’re finished with it. If you don’t want this, you’ll need to use the callback behavior. This hwover is quite clean when using Java 8 thanks to closures:

return dbi.withHandle(handle ->
                          handle.createQuery("SELECT bar FROM foo WHERE bar = :param")
                              .bind("param", "bar")
                              .first(String.class)
);

Custom Parameter Binding

We’ve all seen this in JdbcTemplate:

DateTime now = DateTime.now();
Map<String, Object> params = new HashMap<>();
params.put("param", new Timestamp(now.getDate().getTime()));
return jdbcTemplate.queryForObject("SELECT bar FROM foo WHERE bar = :param", params, String.class);

The parameter types are quite limited to those supported by default in plain JDBC, which means simple types, String and java.sql types. With JDBI, you can bind custom argument classes by implementing a custom Argument class. In the case above, this would look like this:

public class LocalDateTimeArgument implements Argument {

    private final LocalDateTime localDateTime;

    public LocalDateTimeArgument(LocalDateTime localDateTime) {
        this.localDateTime = localDateTime;
    }

    @Override
    public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
        statement.setTimestamp(position, new Timestamp(localDateTime.toEpochSecond(ZoneOffset.UTC)));
    }
}

With JBDI you can then do this:

Handle handle = jdbi.open();
DateTime now = DateTime.now();
return handle
    .createQuery("SELECT bar FROM foo WHERE bar = :param")
    .bind("param", new LocalDateTimeArgument(now))
    .first(String.class);
handle.close();

However, you can also register an ArgumentFactory that builds the needed Argument classes when needed, which enables you to just bind a LocalDateTime value directly.

Custom DAOs

Those of us that are lucky enough to use Spring Data know that it supports a very nice feature: repositories. However, if you’re using JDBC, you shit out of luck, because this feature doesn’t work with plain JDBC.

JDBI however has a very similar feature. You can write interfaces and annotate the method just like Spring Data does. For example, you can create an interface like this:

public interface FooRepository {
    @SqlQuery("SELECT bar FROM foo where bar = :param")
    public String getBar(@Bind("param") String bar);
}

You can then create a concrete instance of that interface with JDBI and use the methods as if they were implemented.

FooRepository repo = jdbi.onDemand(FooRepository.class);
repo.getBar("bar");

When creating an instance onDemand you don’t need to close the repository instance after you’re done with it. This also means you can reuse it as a Spring Bean!

Other Things and Conclusion

There is a myriad of features I haven’t touched yet, such as object binding, easy batching, mixins and externalized named queries. These features combined with those I mentioned earlier make JDBI a compelling alternative to JdbcTemplate. Due to the fact it works nicely in combination with Spring’s transaction system, there’s little effort needed to start using it. Most objects in JDBI are threadsafe and reusable as singletons so they can be defined as Spring beans and injected where needed.

If you’re looking into doing plain JDBC work and need something different than JDBC template, have a look at JDBI. It’s definitely going in my toolbox.

Spring Framework

Published at DZone with permission of Lieven Doclo, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Best Use Java Records as DTOs in Spring Boot 3
  • 10 Things to Know When Using SHACL With GraphDB
  • 5 Steps for Getting Started in Deep Learning
  • Microservices 101: Transactional Outbox and Inbox

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: