Mapping a row from a SQL data to a Java object

前端 未结 9 1174
悲哀的现实
悲哀的现实 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 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() {
        @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.

提交回复
热议问题