Spring 具名参数NamedParameterJdbcTemplate

时间:2023-03-09 04:52:45
Spring 具名参数NamedParameterJdbcTemplate

具名参数:

具名参数:SQL 按名称(以冒号开头)而不是按位置进行指定. 具名参数更易于维护, 也提升了可读性. 具名参数由框架类在运行时用占位符取代

我们之前一直是用JDBCTemplate  进行Sql语句的 拼写 , 但是 当 一个行中有 多个 占位符时,很容易 搞混哪个值 是 哪个值。 那我们可以使用具名参数。

如何使用具名参数?

1. 在 xml 文件中加入对具名参数的支持

注意具名参数只能 使用 constructor-arg  并且必须对 dataSource 赋值

<!-- 具名参数 必须要有参数的构造器   没有无参的 -->
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg name="dataSource" ref="DataSource"></constructor-arg>
</bean>

applicationContext.xml

2. 在Java 类中引入 具名参数

import java.util.HashMap;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.EmptySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository; import com.myth.springJDBC.exception.AddFailedException;
import com.myth.springJDBC.po.Employee; @Repository
public class EmployeeDao {
@Autowired
private JdbcTemplate jdbcTemplate; @Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private String sql;

  //这个使用的 是 传统的 JdbcTemplate
public Employee getEmployee(int id) {
sql = "Select * from employees where id = ?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
Employee employee = jdbcTemplate.queryForObject(sql, rowMapper,id);
return employee;
} //引入一个 空 的Map EmptySqlParameterSource.INSTANCE
public Integer getCount() {
sql = "select count(*) from employees";
int result = namedParameterJdbcTemplate.queryForObject(sql, EmptySqlParameterSource.INSTANCE, Integer.class);
return result;
}
/*这里也可以使用BeanPropertySqlParameterSource
* 这个意思就是把Map 转换为对象 来对待
*/
public void insertEmployee(Employee employee) {
sql = "INSERT INTO employees values (:ID,:ln,:email,:departID)";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("ID", employee.getId());
paramMap.put("ln", employee.getLast_name());
paramMap.put("email", employee.getEmail());
paramMap.put("departID", employee.getDept_id()); try {
namedParameterJdbcTemplate.update(sql, paramMap);
System.out.println("添加成功");
} catch (Exception e) {
throw new AddFailedException("添加失败");
}
}    //要注意具名参数要和Bean中的属性值要一致。
   public void updateEmployee(Employee employee) {
      sql = "UPDATE employees set LAST_NAME =:last_name,EMAIL=:email,DEPT_ID =:dept_id WHERE ID = :id";
      SqlParameterSource paramSource = new BeanPropertySqlParameterSource(employee);
      try {
       namedParameterJdbcTemplate.update(sql, paramSource);
       System.out.println("修改成功");
      } catch (Exception e) {
       System.out.println(e.toString());
       throw new AddFailedException("修改失败");
      }
     }    /* 这样子 会报错
* public void deleteEmployee(int id) {
sql = "DELETE FROM EMPLOYEES WHERE ID = :ID";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("ID", id);
try {
namedParameterJdbcTemplate.update(sql, paramMap);
System.out.println("删除成功");
} catch (Exception e) {
throw new AddFailedException("删除失败");
}
}*/
//必须传入Employee 只传入int id 会报错
public void deleteEmployee(Employee employee) {
sql = "DELETE FROM EMPLOYEES WHERE ID = :ID";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("ID", employee.getId());
try {
namedParameterJdbcTemplate.update(sql, paramMap);
System.out.println("删除成功");
} catch (Exception e) {
throw new AddFailedException("删除失败");
}
}
}

3.然后写Junit Test 类

 package com.myth.springJDBC;

 import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.myth.springJDBC.dao.EmployeeDao;
import com.myth.springJDBC.po.Employee;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestJDBC {
@Autowired
private EmployeeDao employeeDao; @Test
public void testQuery() {
System.out.println(employeeDao.getEmployee(12));
} @Test
public void testInsert() {
Employee employee = new Employee();
employee.setId(12);
employee.setLast_name("FF");
employee.setEmail("FF@email.com");
employee.setDept_id(4); employeeDao.insertEmployee(employee);
} @Test
public void testUpdate() {
Employee employee = new Employee();
employee.setId(12);
employee.setLast_name("FFF");
employee.setEmail("FF@email.com");
employee.setDept_id(4); employeeDao.updateEmployee(employee);
} @Test
public void testDelete() {
Employee employee = new Employee();
employee.setId(12);
employeeDao.deleteEmployee(employee);
} @Test
public void testGetCount() {
System.out.println(employeeDao.getCount());
}
}

Junit