在JDBC模板中使用具名参数
<!-- 配置NamedParameterJdbcTemplate,该对象可以使用具名参数,其没有无参数的构造器,所以必须为其构造器指定参数 -->
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"
>
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
/*
* 可以为参数起名字
* 1.好处:若有多个参数,则不用再去对应位置,直接对应参数名,便于维护
* 2.缺点:较为麻烦
*/
@Test
public void testNamedParameterJdbcTemplate(){
String sql = "insert into employees(last_name,email,dept_id) values(:ln,:email,:deptid)";
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("ln","FF");
paramMap.put("email","ff@cloud.com");
paramMap.put("deptid",2);
namedParameterJdbcTemplate.update(sql,paramMap);
}
以对象的属性作为别名
/**
* @program: spring-1
* @description: Employee
* @author: fish
* @create: 2020-03-09 15:20
**/
public class Employee {
private Integer id;
private String lastName;
private String email;
private int deptId;
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", department=" + department +
", deptId=" + deptId +
'}';
}
}
/*
* 使用具名参数时,可以使用update(String sql,SqlParameterSource paramSource)方法进行更新操作
* 1.SQL语句中的参数名和类的属性一致!
* 2.使用SqlParameterSource的BeanPropertySqlParameterSource实现类作为参数
*/
@Test
public void testNamedParameterJdbcTemplate2(){
String sql = "insert into employees(last_name,email,dept_id) values(:lastName,:email,:deptId)";
Employee employee = new Employee();
employee.setLastName("XYZ");
employee.setEmail("xyz@sina.com");
employee.setDeptId(3);
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(employee);
namedParameterJdbcTemplate.update(sql,parameterSource);
}
网友评论