Loading...

Yet Another Fluent JDBC Wrapper in 200 Lines of Code

View: 245    Dowload: 0   Comment: 0   Post by: admin   Category: Javascript   Fields: Other

Download  yet-another-fluent-jdbc.zip (30.68 KB)

You need to Sign In to download the file yet-another-fluent-jdbc.zip
If you do not have an account then Sign up for free here

Introduction

Those who are not convinced to use Hibernate to manage persistence are forced to use plain old JDBC API. Though powerful, it requires lot of typing to get it right. For example, retrieving user data from database often requires such code snippet:

final List<User> result = new ArrayList<>();
final PreparedStatement s = 
        conn.prepareStatement("select name, password from user where name = ?");
try{
   s.setString(1, "adam");
   final ResultSet rs = s.executeQuery();
   try {
      result.add(new User(rs.getString(1), rs.getString(2)));
   } finally {
      rs.close();
   }
} finally {
   s.close();
}

With Java 7’s try-with-resources, this code is a little shorter:

List<User> list = new ArrayList<>();
try (final PreparedStatement s = c.prepareStatement
("select name, password from users where name = ?")) {
    s.setString(1, "adam");
    try (final ResultSet rs = s.executeQuery()) {
        list.add(new User(rs.getString(1), rs.getString(2)));
    }
}

Even though it is a progress, it is not what most would describe as "elegant". With Java 8’s lambda expressions and fluent API pattern, it can be minimized to so called "on-liner" that looks something like this:

List<User> list2 = using(c).prepare("select name, password from users where name = ?").
              set("Adam").andMap(rs -> new User(rs.getString(1), rs.getString(2)));

Goal

There are numerous approaches to this (jcabi-jdbcfluent-jdbcfluent-jdbcJdbcTemplate, …), but all of them seem a little "big". The goal of this version was a simple one.

Create a fluent JDBC wrapper, that streamlines 80% of JDBC use cases, in just a single source file.

The result is a 200 lines of code (after stripping comments and blank lines) that allows you to express most common JDBC use case in a compact way.

Usage

The wrapper uses static imports (in form of import static fluentJDBC.FluentConnection.*;), fluent method chaining, with implicit parameter index incrementation and functional interfaces which allow lambda expression as parameters to andMapandReduse and forEach methods. The examples of FluentConnectionusage are listed below:

Connection c = null; // we surely should have initializeded this :)

//FluentJDBC - single value retrieval
Optional<User> user = using(c).prepare("select name, password from users where name = ?").
 set("Adam").andMapOne(rs -> new User(rs.getString(1), rs.getString(2)));

//FluentJDBC - result printing
using(c).prepare("select name, password from users where name = ?").
 set("Adam").andForEach(rs -> System.out.println(rs.getString(1)));

// FluentJDBC - aggregation in application - inefficient example
String str = using(c).prepare("select name, password from users where name = ?").
 set("Adam").andReduce("", (acc, rs) -> acc + "name: " + rs.getString(1));

//FluentJDBC - insertion (works for modification and deletion as well)
using(c).prepare("insert into users values (?,?,?)").set(1).set("Adam").
 set("password").andUpdate();

//FluentJDBC - insertion returning autogenerated primary key
Integer id = (Integer) using(c).
 prepareWithKey("insert into users(name, password) values (?,?)").
 set("Adam").set("secret").andUpdateReturningKey();

//FluentJDBC - custom parameter setting code
using(c).prepare("insert into users values (?,?,?)").set(1).set("Adam").
 set((s, index) -> s.setString(index, "secret")).andUpdate();

//FluentJDBC - custom PreparedStatement modification
using(c).prepare("insert into users values (?,?,?)").set(1).
 set("Adam").set("password").
 apply((s) -> s.setCursorName("c1")).andUpdate();

This project is a BSD licensed, single file (FluentConnection.java), lightweight wrapper that you can include in your project and use. It is by no means a complete JDBC wrapper, but I encourage you to extend it to meet your own needs.

Yet Another Fluent JDBC Wrapper in 200 Lines of Code

Those who are not convinced to use Hibernate to manage persistence are forced to use plain old JDBC API. Though powerful, it requires lot of typing to get it right. For example, retrieving user data from database often requires such code snippet:

Posted on 28-02-2018 

Comment:

To comment you must be logged in members.

Files with category

  • Mini Youtube Using ReactJS

    Mini Youtube Using ReactJS

    View: 169    Download: 3   Comment: 0

    Category: Javascript     Fields: none

    This is one the best starter for ReactJS. MiniYoutube as the name suggests is a youtube like website developed using reactJS and youtube API. This project actually let's you search , play and list youtube videos. Do check it out and start learning...

  • AngularJS and REST API

    AngularJS and REST API

    View: 315    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    This is a tutorial for those interested in a quick introduction to AngularJS and REST API. We will build the familiar Periodic Table of the Elements found in every chemistry textbook, and allow the user to select a Chemical Element by clicking on...

  • Collective Intelligence, Recommending Items Based on Similar Users' Taste

    Collective Intelligence, Recommending Items Based on Similar Users' Taste

    View: 250    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Using Collaborative Filtering to find people who share tastes, and for making automatic recommendations based on things that other people like.

  • Think Like a Bird for Better Parallel Programming

    Think Like a Bird for Better Parallel Programming

    View: 226    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Coding an application to run in parallel is hard, right? I mean, it must be hard or we’d see parallel programs everywhere. All we'd see are slick parallel apps that use every available core effortlessly. Instead multi-threaded apps are the exception...

  • Getting Started with the Bing Search APIs

    Getting Started with the Bing Search APIs

    View: 249    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Bing Search API is a set of REST interfaces that find web pages, news, images, videos, entities, related searches, spelling corrections, and more in response to queries from any programming language that can generate a web request. Applications that...

  • Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    View: 569    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Continuous in-line request/result batching, real-time stream sending/processing, asynchronous data transferring and parallel computation for best performance and scalability

  • Iteration Over Java Collections with High Performance

    Iteration Over Java Collections with High Performance

    View: 219    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Java developers usually deal with Collections such as ArrayList, HashSet, Java 8 come with lambda and streaming API helps us to easily work with Collections. In most cases, we work with few thousands of items and performance isn't a concern. But in...

  • SR2JLIB - A Symbolic Regression Library for Java

    SR2JLIB - A Symbolic Regression Library for Java

    View: 215    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Grammar-Guided Genetic Programming library featuring: multi-threading, just-in-time compilation of individuals, dynamic class loading, and JNI interfacing with C/C++ code

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd