Loading...

Yet Another Fluent JDBC Wrapper in 200 Lines of Code

View: 178    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: 25    Download: 2   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...

  • Angular 6 Starter with Laravel 5.6 API Service

    Angular 6 Starter with Laravel 5.6 API Service

    View: 62    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    Angular 6 and Laravel 5.6 This project is a starter for creating interface with Angular using bootstrap && css && sass and using Laravel 5.6 for api requests. Demo Installation This project is divided in two parts (projects) and before use them you...

  • Simple Richtext Editor Based on pellJS

    Simple Richtext Editor Based on pellJS

    View: 26    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    A simple visual editor for websites using the pell javascipt. It also has the option to switch between visual editor mode and source code mode. I will upload an update for new functionality soon. Source Code Editor Visual Editor

  • Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    View: 37    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    With the Active Reports Server, you can have a multi-tenant environment where users from various departments, companies, or other specifications can log in, view their reports (and only their reports), export the data, or set up a distribution...

  • AngularJS and REST API

    AngularJS and REST API

    View: 204    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: 168    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: 157    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: 169    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...

 
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