[Java 8 & Spring JDBC] simplifies DAO with spring jdbc and lambda expressions

Source: Internet
Author: User
Tags getmessage

Simplifying DAO with spring jdbc and lambda expressions

If you need to insert an item record into the database, then there is code similar to the following:

The entity type for item corresponds to:

publicclass Item {    publicint name;    public BigDecimal price;}
 Public void Create(Item Item)throwsIOException {PreparedStatement PS =NULL;Try{Connection con = Template.getdatasource (). getconnection (); PS = Con.preparestatement ("INSERT into items [name, price, Prc_date] VALUES (?,?,?, Now ())"); Ps.setstring (1, item.name); Ps.setbigdecimal (2, Item.price);  Ps.executeupdate (); }Catch(SQLException e) {Throw NewIOException (e); }finally{if(PS! =NULL) {Try{Ps.close (); }Catch(SQLException e)      {Logger.warn (E.getmessage (), E); }    }  }}

The type of the template is org.springframework.jdbc.core.JdbcTemplate .
If you use the Update method provided by the JdbcTemplate type, you can make the above code much simpler:

publicvoidcreatethrows IOException {  template.update(      "insert into items (name, price, prc_date) values (?, ?, now())",      item.name, item.price);}

However, this overload of using the Update method directly is not the quickest. You can use public int update(String sql, PreparedStatementSetter pss) this overload to get a better run speed:

publicvoidcreatethrows IOException {  template.update(      "insert into item (name, price, prc_date) values (?, ?, now())",      new PreparedStatementSetter() {        @Override        publicvoidsetValuesthrows SQLException {          ps.setString(1, item.name);          ps.setBigDecimal(2, item.price);        }      });}

If you use a lambda expression in Java 8, the code above still has a simplified space:

publicvoidcreate(finalthrows IOException {  template.update(      "insert into items (name, price, prc_date) values (?, ?, now())",      ps -> {        ps.setString(1, item.name);        ps.setBigDecimal(2, item.price);      });}

Similarly, for SELECT statements can be simplified by jdbctemplate and lambda expressions, and the simplified, cumbersome try-catch-finally statements can be effectively eliminated:

 PublicItemFindbyitemname(String name)throwsIOException {PreparedStatement PS =NULL; ResultSet rs =NULL;Try{Connection con = Template.getdatasource (). getconnection (); PS = Con.preparestatement ("SELECT Name, price from items where name =?"); Ps.setstring (1, name); rs = Ps.executequery ();if(Rs.next ()) {return NewItem (Rs.getstring (1), Rs.getbigdecimal (2)); }return NULL; }Catch(SQLException e) {Throw NewIOException (e); }finally{if(rs! =NULL) {Try{Rs.close (); }Catch(SQLException e)      {Logger.warn (E.getmessage (), E); }    }if(PS! =NULL) {Try{Ps.close (); }Catch(SQLException e)      {Logger.warn (E.getmessage (), E); }    }  }}

The simplified code looks like this:

publicfindItemByNamethrows IOException {  return DataAccessUtils.requiredSingleResult(      template.query("select name, price from items where name = ?",          ps -> {              ps.setString(1, name);          },          new Item(rs.getString(1), rs.getBigDecimal(2))          ));}

Because template.query a list collection is returned, it needs to be used DataAccessUtils.requiredSingleResult to obtain a unique object.

Other types of SQL statements, such as update and delete, can be greatly simplified by using spring jdbctemplate and lambda expressions.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Java 8 & Spring JDBC] simplifies DAO with spring jdbc and lambda expressions

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.