Mapping a row from a SQL data to a Java object

前端 未结 9 1186
悲哀的现实
悲哀的现实 2021-02-06 02:34

I have a Java class with instance fields (and matching setter methods) that match the column names of a SQL database table. I would like to elegantly fetch a row from the table

9条回答
  •  别那么骄傲
    2021-02-06 03:13

    If you do not want to use any other framework, you can create standard mapping method and use it after every Result.

    public class CurrencyDAO(){
    
            public Currency findById(int id) {
            String sql = "SELECT * FROM CCR.CURRENCY WHERE id = ?";
            Currency currency = null;
            Connection c = null;
            try {
                c = DBConnection.getConnection();
                PreparedStatement ps = c.prepareStatement(sql);
                ps.setInt(1, id);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    currency = processRow(rs);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                DBConnection.close(c);
            }
            return currency;
        }
    
    
        protected Currency processRow(ResultSet rs) throws SQLException {
            Currency currency = new Currency();
            currency.setId(rs.getInt("id"));
            currency.setEUR(rs.getString("EUR"));
            currency.setUSD(rs.getString("USD"));
            currency.setRate(rs.getString("rate"));     
            return currency;
    
        }
    }
    

提交回复
热议问题