Java8 Learning Journey 2---Lambda-based JDBC programming

Source: Internet
Author: User
Tags stream api

Java8 lambda expressions are really a good feature. But on which occasions to use. In fact, it needs careful consideration. We certainly cannot use it for use, but we need to find practical and useful occasions. In JDBC programming, such as query statements, you first need to query the parameter binding, followed by the processing of the returned result set, these two operations are each query is different, and get the JDBC connection, prepare PreparedStatement, and release resources are all the same, This is a great scenario for a lambda expression application.

Before discussing the detailed implementation details, you want to discuss the JDBC problem first.

Now believe that more than 90% of Java program apes will no longer use JDBC, the basic use of some or mapping mechanism. such as hibernate, persistent API, etc., using the so-called OO way to operate the database.

But in fact, such a way is very good in theory, in practical applications there are very big problems, especially in the case of big data at the moment. It is very undesirable to bind data and programs together, and at the same time, with or mapping, the abstraction of the data operation in terms of functionality and performance is completely not comparable to SQL, so the direct use of JDBC is worth considering. Today's struggle for language is basically the most popular frame of contention in the language, and the Java language is basically ssh and JBoss, because of these two unusually popular and unwieldy frameworks. So that Java basically fade out of the Internet Application development field. In fact, the combination of the Java NiO 2 and the recent lambda expression, Stream API new features. It is entirely possible to write a better framework than node. JS, just a pity that the Java development community is in the habit of thinking. It is very difficult to make this possible into reality.

Okay, here we are. We first need to construct a SQL query if we need to query the T_user table in the database, including USER_ID, user_name, Nick_name, birthday, and so on. Find records with user_id less than 10000.

First we define the value object:

public class UserInfo {public    long getUserId () {        return userId;    }    public void Setuserid (long userId) {        this.userid = userid;    }    Public String GetUserName () {        return userName;    }    public void Setusername (String userName) {        this.username = userName;    }    Public String Getnickname () {        return nickname;    }    public void Setnickname (String nickname) {        this.nickname = nickname;    }    Public Calendar Getbirthday () {        return birthday;    }    public void Setbirthday (Calendar birthday) {        this.birthday = birthday;    }    Private long userId = 0;    Private String userName = null;    Private String nickname = null;    Private Calendar birthday = null;}
Next we define the functions that get and release the JDBC Connection:

    Private Connection getconnection () {        Connection conn = null;        try {            class.forname ("Com.mysql.jdbc.Driver");            conn = Drivermanager.getconnection ("Jdbc:mysql://localhost:3306/wkydb?")

user=wky&password=wky123& "+ " useunicode=true&characterencoding=utf-8& "+ " AutoReconnect =true&failoverreadonly=false "); } catch (Exception e) { system.exit (0); } return conn; } private void CloseConnection (Connection conn) { try { if (conn! = null &&!conn.isclosed ()) { conn . Close (); } } catch (SQLException e) { //TODO auto-generated catch block e.printstacktrace (); } }

Let's define the parameter-bound function interface:

@FunctionalInterfacepublic interface fparambinder<t> {public    void Bindparams (PreparedStatement stmt, T param) throws SQLException;}
Next we define the function interface that receives the return result:

@FunctionalInterfacepublic interface fresetsetter<t> {public    list<t> getresultset (ResultSet rst) Throws SQLException;}
The following is a detailed implementation function of the SQL query:

    Public <T> list<t> executeQuery (String sql, fparambinder<t> Binder, T cond, fresetsetter<t> SE        tter) {Connection conn = getconnection ();        PreparedStatement stmt = null;        ResultSet rst = null;        list<userinfo> items = new arraylist<userinfo> ();        USERINFO item = NULL;        List<t> RECs = null;            try {stmt = conn.preparestatement (sql); Binder.bindparams (stmt, cond);            Call parameter binding function Interface rst = Stmt.executequery (); RECs = Setter.getresultset (RST);        Get return result set} catch (SQLException e) {e.printstacktrace ();                } finally {try {if (rst! = null) {rst.close ();                } if (stmt! = null) {stmt.close ();        }} catch (Exception ex) {}} closeconnection (conn);    Return RECs; }
This function is implemented in a different query than in normal JDBC programming. The two parts of the parameter binding and the receiving result set are implemented through the passed-in function interface variable, so the code is very concise.

The following are calls to the above functions when other functions call SQL queries, such as the following:

    public void Testit () {String-sql = "Select user_id, user_name, Nick_name, birthday from T_user where USER_ID&L        t;? "; fparambinder<userinfo> Binder = (preparedstatement stmt, UserInfo param), {stmt.setlong (1, para        M.getuserid ());        };        UserInfo cond = new UserInfo ();        Cond.setuserid (10000000L); Fresetsetter<userinfo> setter = (ResultSet rst), {list<userinfo> items = new Arraylist<use            Rinfo> ();            USERINFO item = NULL;                while (Rst.next ()) {item = new UserInfo ();                Item.setuserid (Rst.getlong (1));                Item.setusername (rst.getstring (2));            Items.Add (item);        } return items;        };        List<userinfo> RECs = executeQuery (sql, Binder, cond, setter);        System.out.println ("size=" + recs.size () + "!"); for (UserInfo u:recs) {System.out.println ("U:" + u.getusername () + "-"+ u.getuserid () +"! "); }    }
Mentioned above. The caller needs to specify the query SQL statement, define the parameter binding function interface variable, the result set receives the function interface variable, and then calls the above ExecuteQuery method, can obtain to the result set. Then you will be able to do the next step.

Java8 Learning Journey 2---Lambda-based JDBC programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.