zoukankan      html  css  js  c++  java
  • spring之操作数据库之使用NamedParameterJdbcTemplate(具名参数)

    接上一节:https://www.cnblogs.com/xiximayou/p/12167150.html。

    在applicationContext.xml中配置namedParameterJdbcTemplate。

        <!-- 配置 NamedParameterJdbcTemplate, 该对象可以使用具名参数, 其没有无参数的构造器, 所以必须为其构造器指定参数 -->
        <bean id="namedParameterJdbcTemplate"
            class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
            <constructor-arg ref="dataSource"></constructor-arg>    
        </bean>

    在JDBCTest.java中进行测试:

        private ApplicationContext ctx = null;
        private JdbcTemplate jdbcTemplate;
        private EmployeeDao employeeDao;
        private DepartmentDao departmentDao;
        private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
        {
            ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
            employeeDao = ctx.getBean(EmployeeDao.class);
            departmentDao = ctx.getBean(DepartmentDao.class);
            namedParameterJdbcTemplate = ctx.getBean(NamedParameterJdbcTemplate.class);
        }
        
        /**
         * 可以为参数起名字. 
         * 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@atguigu.com");
            paramMap.put("deptid", 2);
            
            namedParameterJdbcTemplate.update(sql, paramMap);
        }
        /**
         * 使用具名参数时, 可以使用 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,:dpetId)";
            
            Employee employee = new Employee();
            employee.setLastName("XYZ");
            employee.setEmail("xyz@sina.com");
            employee.setDpetId(3);
            
            SqlParameterSource paramSource = new BeanPropertySqlParameterSource(employee);
            namedParameterJdbcTemplate.update(sql, paramSource);
        }
  • 相关阅读:
    sql行列互转
    用户角色权限设计思路
    树节点类型数据的Datatable转Json
    [C#]最简单的Base64加密解密
    WEB打印控件Lodop(V6.x)使用说明及样例
    js代码 设为首页 加入收藏
    Json字符转化成对象
    C++函数返回值为const
    7.双指针(two pointer)
    线程同步与锁
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12167219.html
Copyright © 2011-2022 走看看