首页 文章

关于RowMapper在Spring Framework应用程序中使用JDBC的一些疑问

提问于
浏览
15

我正在研究如何在Spring Framework中使用JDBC对数据库执行查询 .

我正在学习本教程:http://www.tutorialspoint.com/spring/spring_jdbc_example.htm

在本教程中,我定义了一个 StudentDAO 接口,它只定义了我想要的CRUD方法 .

然后定义 Student 类,它是我想要在Student数据库表上保留的实体 .

然后定义 StudentMapper 类,它是 RowMapper 接口的特定实现,在这种情况下,用于将 ResultSet (由查询返回)中的特定记录映射到 Student 对象 .

然后我有了 StudentJDBCTemplate ,它支持我的 StudentDAO 接口的实现,在这个类中我实现了接口中定义的CRUD方法 .

好的,现在我怀疑 StudentMapper 类是如何工作的:在这个 StudentJDBCTemplate 类中定义了返回Student数据库表中所有记录列表的方法,这个:

public List<Student> listStudents() {
      String SQL = "select * from Student";
      List <Student> students = jdbcTemplateObject.query(SQL, 
                                new StudentMapper());
      return students;
   }

你怎么看,这个方法返回一个List of Student对象并按以下方式工作:

它首先要做的是在SQL字符串中定义 return all record in the Student database table 的查询 .

然后通过jdbcTemplateObject对象上的查询方法调用执行此查询(即 JdbcTemplate Spring类**的istance)

此方法有两个参数:SQL String(包含必须执行的SQL查询)和一个新的 StudentMapper 对象,它接受查询返回的 ResultSet 对象并将其记录映射到新的Student对象上

在这里阅读:http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html说: Execute a query given static SQL, mapping each row to a Java object via a RowMapper.

我的怀疑是因为我的 StudentMapper 使用 mapRow() 方法在Student对象上映射ResultSet记录,这是代码:

package com.tutorialspoint;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student> {
   public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
      Student student = new Student();
      student.setId(rs.getInt("id"));
      student.setName(rs.getString("name"));
      student.setAge(rs.getInt("age"));
      return student;
   }
}

那么,谁叫这个 mapRow 方法呢?它是由Spring Framework自动调用的吗? (因为在这个例子中永远不会手动调用...)

TNX

安德里亚

然后,此查询由jdbcTemplateObject对象上的查询方法调用执行(即 JdbcTemplate Spring类**的istance)

4 回答

  • 2

    RowMapper 的实例传递给 JdbcTemplate 方法时

    List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
    

    JdbcTemplate 取决于您调用的方法,将在内部使用映射器以及从JDBC连接获取的结果集,以创建所请求类型的对象 . 例如,由于您调用了 JdbcTemplate#query(String, RowMapper) ,该方法将使用您的String SQL查询数据库,并将循环遍历 ResultSet 中的每个"row",如下所示:

    ResultSet rs = ... // execute query
    List<Student> students = ...// some list
    int rowNum = 0;
    while(rs.next()) {
        Student student = rowMapper.mapRow(rs, rowNum);
        students.add(student);
        rowNum++;
    }
    
    return students;
    

    因此, SpringJdbcTemplate 方法将使用您提供的 RowMapper 并调用其 mapRow 方法来创建预期的返回对象 .

    您可能希望看看Martin Fowler的Data MapperTable Data Gateway一起了解这些事物是如何分布并提供low coupling的 .

  • 4

    这是我与BeanPropertyRowMapper一起使用的典型模式 . 它节省了大量的编码 . 您的查询需要对每列进行别名以匹配类中的属性名称 . 在这种情况下, species_name as species 和其他列名称恰好匹配 .

    public class Animal {
        String species;
        String phylum;
        String family;
        ...getters and setters omitted
    }
    
    @Repository
    public class AnimalRepository {
        private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    
        @Autowired
        public void setDataSource(DataSource dataSource) {
            this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
        }
    
        public List<Animal> getAnimalsByPhylum(String phylum) {
            String sql = " SELECT species_name as species, phylum, family FROM animals"
                     +" WHERE phylum = :phylum";
    
            Map<String, Object> namedParameters = new HashMap<String, Object>();
            namedParameters.put("phylum", phylum);
            SqlParameterSource params = new MapSqlParameterSource(namedParameters);
            List<Animal> records = namedParameterJdbcTemplate.query(sql,
                    params, BeanPropertyRowMapper.newInstance(Animal.class));
    
            return records;
        }
    }
    

    另一种方法是在每行需要更多自定义时使用RowMapper(此示例仅使用匿名类):

    List<Animal> records = namedParameterJdbcTemplate.query(sql,
                params, new RowMapper<Animal>(){
            public Animal mapRow(ResultSet rs, int i) throws SQLException {
                Animal animal = new Animal();   
                animal.setSpecies(rs.getString("species_name"));
                if (some condition) {
                    animal.setPhylum(rs.getString("phylum"));
                } else {
                    animal.setPhylum(rs.getString("phylum")+someThing());
                }
                animal.setFamily(rs.getString("family"));
    
                return animal;
            }
        });
    
  • 22

    在Spring中使用RowMapper

    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import org.springframework.jdbc.core.RowMapper;
    
    public class RowsMap implements RowMapper<EmpPojo>{
    
        @Override
        public EmpPojo mapRow(ResultSet rs, int counts) throws SQLException {
            EmpPojo em=new EmpPojo();
            em.setEid(rs.getInt(1));
            em.setEname(rs.getString(2));
            em.setEsal(rs.getDouble(3));
    
            return em;
        }
    
    }
    
    Finally in Main class
    
    List<EmpPojo> lm=jt.query("select * from emps", new RowsMap());
    for(EmpPojo e:lm)
    {
        System.out.println(e.getEid()+" "+e.getEname()+" "+e.getEsal());
    }
    
  • 1

    那么,谁调用这个mapRow方法呢?它是由Spring Framework自动调用的吗? (因为在这个例子中永远不会手动调用...)

    这是由spring框架自动调用的 . 所有你需要的是指定

    连接参数,SQL语句声明参数并提供参数值为每次迭代执行工作 .

相关问题