[Java 8 & Spring JDBC] 使用Spring JDBC和Lambda運算式簡化DAO

來源:互聯網
上載者:User

標籤:lambda   spring   jdbc   java-8   

使用Spring JDBC和Lambda運算式簡化DAO

如果你需要向資料庫中插入一條Item記錄,那麼會有類似下面的代碼:

Item對應的實體類型為:

public class Item {    public int name;    public BigDecimal price;}
public void create(Item item) throws IOException {  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 new IOException(e);  } finally {    if (ps != null) {      try {        ps.close();      } catch (SQLException e) {        logger.warn(e.getMessage(), e);      }    }  }}

其中的template的類型為org.springframework.jdbc.core.JdbcTemplate
如果使用JdbcTemplate類型提供的update方法,可以使上述代碼大幅簡化:

public void create(Item item) throws IOException {  template.update(      "insert into items (name, price, prc_date) values (?, ?, now())",      item.name, item.price);}

但是,直接使用update方法的這一重載並不是最快的。可以使用public int update(String sql, PreparedStatementSetter pss)這一重載來得到更佳的運行速度:

public void create(CartItemRelation item) throws IOException {  template.update(      "insert into item (name, price, prc_date) values (?, ?, now())",      new PreparedStatementSetter() {        @Override        public void setValues(PreparedStatement ps) throws SQLException {          ps.setString(1, item.name);          ps.setBigDecimal(2, item.price);        }      });}

如果使用Java 8的Lambda運算式,上述代碼仍然有簡化的空間:

public void create(final Item item) throws IOException {  template.update(      "insert into items (name, price, prc_date) values (?, ?, now())",      ps -> {        ps.setString(1, item.name);        ps.setBigDecimal(2, item.price);      });}

同樣的,對於SELECT語句也可以通過JdbcTemplate和Lambda運算式簡化,簡化後繁瑣的try-catch-finally語句可以被有效消除:

public Item findByItemName(String name) throws IOException {  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 new Item(rs.getString(1), rs.getBigDecimal(2));    }    return null;  } catch (SQLException e) {    throw new IOException(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);      }    }  }}

簡化後的代碼如下所示:

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

由於template.query返回的是一個List集合,所以還需要使用DataAccessUtils.requiredSingleResult來取得唯一對象。

對於其他類型的SQL語句,如update和delete等,都可以通過使用Spring JdbcTemplate和Lambda運算式進行大幅簡化。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

[Java 8 & Spring JDBC] 使用Spring JDBC和Lambda運算式簡化DAO

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.