Spring JDBCTemplate Query方法查询


queryspringtypessqldaoemail
近日系统有一个打印采购单的功能,发现连续打印多张后,主机宕机,看了下service和dao层的实现,很繁杂,估计原因主要出在组页面资料的时候,循环套循环导致效能下降,然后想想有什么办法可以减少组资料时的一些对象转换,dao层取回来的是map,然后还要转换成vo,然后又循环组资料,google下资料,发现jdbctemplate查询还有个query方法,可以直接在查好后返回你需要的vo,改好上线,不知道对效能有没有帮助,不过这个做法感觉不错,特把文章贴在blog里面,以备后用,呵呵


   
在内部建立内联类实现RowMapper接口
package hysteria.contact.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import hysteria.contact.dao.ItemDAO;
import hysteria.contact.domain.Item;
public class ItemDAOImpl implements ItemDAO {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  this.jdbcTemplate = jdbcTemplate;
}
public Item insert(Item item) {
  String sql = "INSERT INTO items(user_id,name,phone,email) VALUES(?,?,?,?)";
  Object[] params = new Object[]{item.getUserId(),item.getName(),item.getPhone(),item.getEmail()};
  int[] types = new int[]{Types.INTEGER,Types.VARCHAR,Types.CHAR,Types.VARCHAR};
  jdbcTemplate.update(sql,params,types);
  return item;
}
public Item update(Item item) {
  String sql = "UPDATE items SET name = ?, phone = ?, email = ? WHERE id = ?";
  Object[] params = new Object[] {item.getName(),item.getPhone(),item.getEmail(),item.getId()};
  int[] types = new int[] {Types.VARCHAR,Types.CHAR,Types.VARCHAR,Types.VARCHAR,Types.INTEGER};
  jdbcTemplate.update(sql,params,types);
  return item;
}
public void delete(Item item) {
  String sql = "DELETE FROM items WHERE id = ?";
  Object[] params = new Object[] {item.getId()};
  int[] types = new int[]{Types.INTEGER};
  jdbcTemplate.update(sql,params,types);
}
public Item findById(int id) {
  String sql = "SELECT * FROM items WHERE id = ?";
  Object[] params = new Object[] {id};
  int[] types = new int[] {Types.INTEGER};
  List items = jdbcTemplate.query(sql,params,types,new ItemMapper());
  if(items.isEmpty()){
   return null;
  }
  return (Item)items.get(0);
}
public List<Item> findAll() {
  String sql = "SELECT * FROM items";
  return jdbcTemplate.query(sql,new ItemMapper());
}
public List<Item> findAllByUser(int user_id) {
  String sql = "SELECT * FROM items WHERE user_id = ?";
  Object[] params = new Object[]{user_id};
  int[] types = new int[]{Types.INTEGER};
  List items = jdbcTemplate.query(sql,params,types,new ItemMapper());
  return items;
}
protected class ItemMapper implements RowMapper {
  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
   Item item = new Item();
   item.setId(rs.getInt("id"));
   item.setUserId(rs.getInt("user_id"));
   item.setName(rs.getString("name"));
   item.setPhone(rs.getString("phone"));
   item.setEmail(rs.getString("email"));
   return item;
  }
}
}
posted @ 2013-11-14 17:41  crazy_itman  阅读(2588)  评论(0编辑  收藏  举报