Spring Boot集成JdbcTemplate的问题总结~~

注入数据源

这里采用Spring Boot的java配置注入数据源:

package com.sitech.ddoe.server.common.domain;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
@PropertySource(value = "classpath:jdbc.properties", ignoreResourceNotFound = true, encoding = "utf-8")
public class DataSourceConfig {

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String driverUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl(driverUrl);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }
}

以上代码中,
用@Configuration注解该类,等价与XML中配置beans;
用@Bean标注方法等价于XML中配置bean。
用@PropertySource引入需要的配置文件,解耦合。

使用JdbcTemplate 时只需要直接注入即可:

@Autowired
private JdbcTemplate jdbcTemplate;

JdbcTemplate常用的方法

  • batchUpdate()
返回的数据类型是int[],适用于返回批量执行成功的条数。
  • update()
 返回的数据类型是int,适用于返回执行成功的条数
  • queryForList()
第一种:
List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql, args);

第二种:
return jdbcTemplate.query(sql, args, new RowMapper<ObjectInst>(){

            @Override
            public ObjectInst mapRow(ResultSet rs, int rowNum) throws SQLException {
                ObjectInst obj = new ObjectInst();
                return obj;
            }
        });

遇到的SQLException

  • Column Index out of range, 0 < 1
ResultSet的结果集,索引从1开始,我取值的时候rs.get(0)报错
  • org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 3
一开始接结果集用的是queryForObject(),但是该方法只能接一个对象,
执行sql返回的有三条数据,不能对应。
所以返回数据不确定时需要要queryForList()。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值