使用JdbcTemplate将关系数据库映射到List <object>,每个包含List <object> </object> </object>

时间:2014-09-08 14:52:11

标签: java mysql spring jdbc jdbctemplate

我正在使用Spring MVC和JdbcTemplate以及MySQL数据库。

说我有以下2个表:

table_school

ID    NAME

table_students

ID    NAME    ADDRESS    SCHOOL_ID

我有一个学校POJO,它有以下类变量:

int id, String name, List<Student> students

是否有办法在一个查询中使用JdbcTemplate 检索包含适当的Student对象列表的每个School对象的List?我知道这很容易使用Hibernate实现,但我想使用JdbcTemplate ..

非常感谢!

1 个答案:

答案 0 :(得分:4)

是的,您可以在1个查询中获取所有数据。

简单示例:

class Student {
    int id;
    String name;
    String addr;

    Student(int id, String name, String addr) {
        this.addr = addr;
        this.id = id;
        this.name = name;
    }
}

class School {
    int id;
    String name;
    List<Student> students = new ArrayList<>();

    School(int id, String name) {
        this.id = id;
        this.name = name;
    }

    void addStudent(Student s) {
        students.add(s);
    }
}

/*
 * helper method that gets school from map or create if not present
 */
private School getSchool(Map<Integer, School> schoolMap, int id, String name) {
    School school = schoolMap.get(id);
    if (school == null) {
        school = new School(id, name);
        schoolMap.put(id, school);
    }
    return school;
}

// RUN QUERY

String sql = 
     " select st.ID, st.NAME, st.ADDRESS. s.id, s.name" +
     " from table_students st" +
     "   inner join table_school s on st.school_id = s.id";

    final Map<Integer, School> schoolMap = new HashMap<>();

    jdbcTemplate.query(sql, new RowCallbackHandler() {

        @Override
        public void processRow(ResultSet rs) throws SQLException {

            int studentId = rs.getInt(1);
            String studentName = rs.getString(2);
            String studentAddr = rs.getString(3);
            int schoolId = rs.getInt(4);
            String schoolName = rs.getString(5);

            Student student = new Student(studentId, studentName, studentAddr);

            getSchool(schoolMap, schoolId, schoolName).addStudent(student);
        }
    });

关于获取效果的最后一点:

如果您希望获取许多记录,那么增加 jdbc fetch size 参数几乎总是一个好主意。所以在运行查询之前在jdbcTemplate上设置它:

jdbcTemplate.setFetchSize(200);  // you can experiment with this value

或者如果你使用的是Spring的JdbcDaoSupport,你可以使用这样的模式:

public class MyDao extends JdbcDaoSupport {

    ....

    @Override
    protected void initTemplateConfig() {
        getJdbcTemplate().setFetchSize(200);
    }

}