注入数据源
这里采用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()。