springboot引入jdbcTemplate


1、pom



    org.springframework.boot
    spring-boot-starter-jdbc

2、数据库配置

spring 
  datasource:
  	driver-class-name: com.mysql.jdbc.Driver
  	url: jdbc:mysql://localhost:3306/demo_test?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF8
  	password: root
  	username: root

3、使用

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List testJdbcTemplate(Integer id) {

        // 不用参数,返回list实体类
        String sql = " select * from parent ";
        List query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Parent.class));

        // 有两个参数 (方法1)
        String sqlA = "select * from parent where relation = ? and child = ? ";
        Object[] params = {"父","1"};
        List listA = jdbcTemplate.query(sqlA,params, new BeanPropertyRowMapper<>(Parent.class));

        // 有两个参数 (方法2)
        List listB = jdbcTemplate.query(sqlA,new BeanPropertyRowMapper<>(Parent.class),"父","1");

        // 有两个参数 (方法3)
        ArrayList paramList = new ArrayList<>();
        paramList.add("父");
        paramList.add("1");  
        Object[] args = paramList.toArray();    // list转数组
        List listC = jdbcTemplate.query(sqlA, args,new BeanPropertyRowMapper<>(Parent.class));

        // 返回map
        List> list = jdbcTemplate.queryForList(sqlA, params);

        // 返回一个值
        String sqlC = " select count(*) abc from (select * from parent where relation = ? and child =?) c ";
        Integer integer = jdbcTemplate.queryForObject(sqlC, params, Integer.class);

        // 返回list, 只用到其中一个字段
        String sqlD = "select id,name from parent where relation = ? ";
        List> list1 = jdbcTemplate.queryForList(sqlD,"父");
        // 先过滤空,再提取字段name,转换成String
        List name1 = list1.stream().filter(o -> !ObjectUtils.isEmpty(o.get("name")))
                                .map(o -> (String)o.get("name")).collect(Collectors.toList());

        return null;
    }

jdbcTemplate多数据源配置

在我另一遍文章 druid配置里有写配置

使用:

    @Autowired
    @Qualifier("jdbcTemplate2")
    private JdbcTemplate jdbcTemplate2;

相关