使用Spring Jdbc (2)

1:需要配置数据源

2:需要配置dbcTemplate

3:需要集成JdbcDaoSupport

 

批量更新

public void addBatch(final List<Form> forms){

       final String sql = "insert into tb_user(userName) values(?)";

       getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter(){

           @Override

           public int getBatchSize() {

              return forms.size();           

           }

           @Override

           public void setValues(PreparedStatement ps, int index)

                  throws SQLException {

              Form form  = forms.get(index);

              ps.setString(1, form.getUserName());

           }

          

       });

    }

 

 

查询单个:

 

public Form  testSelectOneByRowCallbackHandler(final int  formId){

       final String sql = "select * from tb_user where userId=?";

       Object[] params = new Object[] { formId};

       final Form form  = new Form();

       getJdbcTemplate().query(sql,params,new RowCallbackHandler(){

           @Override

           public void processRow(ResultSet rs) throws SQLException { 

              form.setUserId(rs.getInt(1));

              form.setUserName(rs.getString(2));

           }

          

       });

       return form;

    }

 

 

 

查询多个

 

[1] public List  testSelectSomeByRowCallbackHandler(final int  formId){

       final String sql = "select * from tb_user where userId=?";

       Object[] params = new Object[] { formId};

        final List<Form> forms  = new ArrayList<Form>();

       getJdbcTemplate().query(sql,params,new RowCallbackHandler(){

           @Override

           public void processRow(ResultSet rs) throws SQLException { 

              Form form  = new Form();

              form.setUserId(rs.getInt(1));

              form.setUserName(rs.getString(2));

              forms.add(form);

           }

          

       });

       return forms;

    }

 

利用RowMapper处理结果集

 

public List  testSelectSomeByRowMapper(final int  formId){

final String sql = "select * from tb_user where userId=?";

Object[] params = new Object[] { formId};

final List<Form> forms  = new ArrayList<Form>();

return getJdbcTemplate().query(sql,params,new RowMapper(){

 

@Override

public Object mapRow(ResultSet rs, int rowNum) throws SQLException {

 

Form form  = new Form();

form.setUserId(rs.getInt(1));

form.setUserName(rs.getString(2));

return form;

}

 

});

}

 

RowCallbackHandler是有状态的,所以不能在多个地方进行复用

RowMapper是无状态的,能在多个地方进行复用

 

查询单个值

getJdbcTemplate().queryForInt(sql);

……


你可能感兴趣的:(使用Spring Jdbc (2))