在spring JDBCTemplate中经常会用到MapSqlParameterSource与BeanPropertySqlParameterSource这两个对象来传递参数,那么这两个对象在使用中有什么区别呢?
MapSqlParameterSource:用于封装传入的参数,多用于查询数据中,如果命名参数与实体类对象属性不一致,可以用此类来映射,类似于map参数映射。
BeanPropertySqlParameterSource:也是用于封装传入参数,多用于对数据库的插入更新删除等操作,如果命名参数与实体类属性一致,则可以使用此类。
共同点是:MapSqlParameterSource与BeanPropertySqlParameterSource对象都是用在spring JDBCTemplate命名参数的封装上,下面是这两个对象的应用场景:
首先增加一个Employee实体类,如下。
public class Employee {
private int id;
private String name;
private int salary;
//getter setter省略。。。
}1:例如我们要修改一条Employee员工数据,EmployeeTest测试类是这样写的,如下。
@Test
public void save(){
Employee emp = new Employee();
emp.setId(4);
emp.setName("赵六");
emp.setSalary(500);
int num = empDao.updateEmployee(emp);
System.out.println(num);
}2:然后我们在EmployeeDaoImpl中实现修改员工数据的方法,如updateEmployee(emp)方法。
public int updateEmployee(Employee e) {
String sqlStr="update employee set name=:name,salary=:salary where id=:id";
MapSqlParameterSource map = new MapSqlParameterSource();
map.addValue("name", e.getName());
map.addValue("salary", e.getSalary());
map.addValue("id", e.getId());
return this.update(sqlStr, map);
}从步骤2中我们可以看到,传入的三个命名参数:name,:salary,:id与我们Employee实体类中的属性是完全一致的,因此我们在上面用MapSqlParameterSource对象来映射参数显得多余了,于是我们可以使用BeanPropertySqlParameterSource对象来封装参数,将步骤2改成如下即可:
public int updateEmployee(Employee emp) {
String sqlStr="update employee set name=:name,salary=:salary where id=:id";
BeanPropertySqlParameterSource beanParam = new BeanPropertySqlParameterSource(emp);
return this.update(sqlStr, beanParam);
}这样就少了很多步骤,但是如果sql语句是这样的话,例如:
String sqlStr="update employee set name=:myName,salary=:mySalary where id=:empId";
我们就必须得用MapSqlParameterSource对象来映射参数了,因为命名参数已经和Employee实体类不一致了,如下:
public int updateEmployee(Employee e) {
String sqlStr="update employee set name=:myName,salary=:mySalary where id=:empId";
MapSqlParameterSource map = new MapSqlParameterSource();
map.addValue("myName", e.getName());
map.addValue("mySalary", e.getSalary());
map.addValue("empId", e.getId());
return this.update(sqlStr, map);
}MapSqlParameterSource与BeanPropertySqlParameterSource的区别就是这样,主要看传入的参数属性是否与sql语句中的命名参数“:xxx”一致。