zoukankan      html  css  js  c++  java
  • 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 类

     1 package com.myth.springJDBC;
     2 
     3 
     4 import org.junit.Test;
     5 import org.junit.runner.RunWith;
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.test.context.ContextConfiguration;
     8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     9 
    10 import com.myth.springJDBC.dao.EmployeeDao;
    11 import com.myth.springJDBC.po.Employee;
    12 @RunWith(SpringJUnit4ClassRunner.class)
    13 @ContextConfiguration(locations="classpath:applicationContext.xml")
    14 public class TestJDBC {
    15     @Autowired
    16     private EmployeeDao employeeDao; 
    17     
    18     @Test
    19     public void testQuery() {
    20         System.out.println(employeeDao.getEmployee(12));
    21     }
    22 
    23     @Test
    24     public void testInsert() {
    25         Employee employee = new Employee();
    26         employee.setId(12);
    27         employee.setLast_name("FF");
    28         employee.setEmail("FF@email.com");
    29         employee.setDept_id(4);
    30         
    31         employeeDao.insertEmployee(employee);
    32     }
    33     
    34     @Test
    35     public void testUpdate() {
    36         Employee employee = new Employee();
    37         employee.setId(12);
    38         employee.setLast_name("FFF");
    39         employee.setEmail("FF@email.com");
    40         employee.setDept_id(4);
    41         
    42         employeeDao.updateEmployee(employee);
    43     }
    44     
    45     @Test
    46     public void testDelete() {
    47         Employee employee = new Employee();
    48         employee.setId(12);
    49         employeeDao.deleteEmployee(employee);
    50     }
    51     
    52     @Test
    53     public void testGetCount() {
    54         System.out.println(employeeDao.getCount());
    55     }
    56 }
    Junit
  • 相关阅读:
    个人作业1——四则运算题目生成程序
    软件工程的实践项目课程的自我目标
    个人附加作业
    个人作业3——个人总结(Alpha阶段)
    结对编程2——单元测试
    个人作业二——英语学习APP 案例分析
    结对编程 (201421123002,201421123006,201421123007)
    四则运算
    软件工程的实践项目课程的自我目标
    个人作业3——个人总结(Alpha阶段)
  • 原文地址:https://www.cnblogs.com/mythdoraemon/p/7613062.html
Copyright © 2011-2022 走看看