时间:2021-07-01 10:21:17 帮助过:28人阅读
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List findAll(){
String sql = "select * from dept";
return jdbcTemplate.queryForList(sql);
}
/*****************************************
* 查询
* @return
*/
public List<Dept> findAllDepts(){
List<Dept> depts = new ArrayList<Dept>();
String sql = "select * from dept where DEPTNAME = ?";
List list = jdbcTemplate.queryForList(sql, new Object[]{"htxx"});
Iterator iterator = list.iterator();
Dept dept = null;
while(iterator.hasNext()){
Map deptsMap = (Map)iterator.next();
dept = new Dept();
dept.setDeptSno(Integer.parseInt(deptsMap.get("DEPTSNO").toString()));
dept.setDeptName(deptsMap.get("DEPTNAME").toString());
dept.setLoc(deptsMap.get("LOC").toString());
depts.add(dept);
}
return depts;
}
/******************************************
* 删除
* @param deptSno
* @return
*/
public int delete(int deptSno){
String sql = "delete from dept where DEPTSNO = ?";
return jdbcTemplate.update(sql, new Object[]{deptSno});
}
/*******************************************
* 插入
* @param dept
* @return
* @throws UnsupportedEncodingException
*/
public int insert(Dept dept) throws UnsupportedEncodingException{
String sql = "insert into dept values(?,?,?)";
return jdbcTemplate.update(sql,
new Object[]{dept.getDeptSno(), dept.getDeptName(),
dept.getLoc()});
}
/*******************************************
* 批量插入
* @param paramsList
*/
public int[] batchInsert(final List<Dept> paramsList){
String sql = "insert into dept values(?,?,?)";
return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Dept dept = paramsList.get(i);
ps.setInt(1, dept.getDeptSno());
ps.setString(2, dept.getDeptName());
ps.setString(3, dept.getLoc());
}
@Override
public int getBatchSize() {
return paramsList.size();
}
});
}
}
二、applicationContext.xml配置,包括连接数据库信息dataSource、Template、dao
然后写一个测试代码进行测试:
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
DeptDao deptDao = (DeptDao)ac.getBean("deptDao");
//以插入单条数据为例
Dept dept = new Dept();
dept.setDeptSno(120);
dept.setDeptName("htxx");
dept.setLoc("NO.18");
int row;
try {
row = deptDao.insert(dept);
System.out.println("row = "+row);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
另外springJDBC中还有一些此处未提到的方法,我个人觉得只要搞明白了如何成功完成springJDBC的配置,使其能够和数据库连接成功,其他的都好说,毕竟人家已经给你定义好方法了,只需要传入正确的参数来调用就行了。
本文出自 “Java菜鸟” 博客,转载请与作者联系!
SpringJDBC - 01
标签:springjdbc