Mapping a row from a SQL data to a Java object

前端 未结 9 1184
悲哀的现实
悲哀的现实 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:05

    Give q2o a try. It is a JPA based object mapper which helps you with many of the tedious SQL and JDBC ResultSet related tasks, but without all the complexity an ORM framework comes with.

    Bind the Student class to its corresponding table:

    @Table(name = "STUDENTS")
    public class Student (
        private String FNAME;
        private String LNAME;
        private String GRADE;
        ...
    )
    

    Select some students by their grade:

    List<Student> students = Q2ObjList.fromClause(Student.class, "GRADE = ?", grade);
    

    Change a student's grade and persist the change to the database:

    student.setGRADE(grade);
    Q2obj.update(student);
    

    q2o is helpful even when you depend on Spring JDBC:

    jdbcTemplate.queryForObject("...", new RowMapper<Student>() {
        @Override
        public Student mapRow(final ResultSet rs, final int rowNum) throws SQLException {
            return Q2Obj.fromResultSet(rs, Student.class);
        }
    });
    

    It is pretty easy, isn't it? Find more about q2o here.

    0 讨论(0)
  • 2021-02-06 03:11

    If you use JDBC that is how it works. If you want to avoid adding columns like this in Java, you may consider using some ORM frameworks.

    0 讨论(0)
  • 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;
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题