標籤: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