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);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM