NamedParameterJdbcTemplate传参的n种写法

没啥技术含量,烂笔头记下来备查!
数据库
NamedParameterJdbcTemplate传参的n种写法_第1张图片

    /**
     * NamedParameterJdbcTemplate
     * 
     * @see [类、类#方法、类#成员]
     */
    @Test
    public void testNamedTemplate()
    {
        String sql;
        List> list;
        
        // 单条件
        sql = "select id, name from student where id<>:id";
        list = namedJdbcTemplate.queryForList(sql, Collections.singletonMap("id", 5));
        logger.info("★★★★ execute: {} ==> {}", sql, list);
        
        // Map传多条件-写法1
        sql = "insert into student(id, name) values(:id, :name)";
        Map params = new HashMap<>();
        params.put("id", 4);
        params.put("name", RandomStringUtils.randomAlphabetic(5));
        int count = namedJdbcTemplate.update(sql, params);
        System.out.println(count);
        
        // SqlParameterSource传多条件-写法2
        sql = "insert into student(id, name) values(:id, :name)";
        SqlParameterSource parameterSource = new MapSqlParameterSource("id", 20).addValue("name", RandomStringUtils.randomAlphabetic(5));
        count = namedJdbcTemplate.update(sql, parameterSource);
        System.out.println(count);
        
        // Java Bean传条件-写法3
        StudentVO vo = new StudentVO();
        vo.setId(5);
        vo.setName(RandomStringUtils.randomAlphabetic(5));
        SqlParameterSource source = new BeanPropertySqlParameterSource(vo);
        count = namedJdbcTemplate.update(sql, source);
        System.out.println(count);
        
        // 查询主键
        vo.setId(6);
        KeyHolder keyHolder = new GeneratedKeyHolder();
        namedJdbcTemplate.update(sql, source, keyHolder);
        String pk = String.valueOf(keyHolder.getKey());
        logger.info("★★★★ pk ==> {}", pk);
        
        // 返回单个对象
        sql = "select id, name from student where id=:id";
        vo = new StudentVO();
        vo.setId(4);
        source = new BeanPropertySqlParameterSource(vo);
        rowMapper = new BeanPropertyRowMapper<>(StudentVO.class);
        StudentVO studentVO = namedJdbcTemplate.queryForObject(sql, source, rowMapper);
        System.out.println(studentVO);
        
        // IN条件
        sql = "select id, name from student where id in (:ids)";
        list = namedJdbcTemplate.queryForList(sql, Collections.singletonMap("ids", Arrays.asList(1, 2, 3, 4, 5)));
        System.out.println(list);
    }

完整项目代码参考: https://gitee.com/00fly/java-code-frame/tree/master/springmvc-jpa-query

你可能感兴趣的:(Spring)