Tuesday, August 25, 2015

Working with Lambda and JDBC

public <T> List<T> getAll(String sql, Function<ResultSet,T> function) {

        final List<T> list = new ArrayList<>();
        try (Connection con = getConeccion()) {
            try (Statement stmt = con.createStatement()) {
                try (ResultSet rs = stmt.executeQuery(sql)) {

                    while (rs.next()) {

                        list.add(function.apply(rs));
                    }
                }

            }
        } catch (SQLException ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        }

        return list;
    }
This is a  generic simple solution for querying to database using JDBC.


And we can use the above snippet in this way:
public List<Country> getAllCountries() {

        return getAll("select * from petcare.country", new Function<ResultSet, Country>() {

            @Override
            public Country apply(ResultSet rs) {
                Country c = new Country();
              
                try {
                  
                    c.setId(rs.getInt("id"));
                    c.setName(rs.getString("name"));
                  
                } catch (SQLException ex) {
                    Logger.getLogger(getClass().class.getName()).log(Level.SEVERE, null, ex);
                }

                return c;
            }
        });
    }

No comments:

Post a Comment