Spring中JdbcTemplate的配置和使用(注解)
1、引入依赖
gradle(这里是编译源码所引入的依赖,如果不是在编译源码的情况下, 就要对spring的包进行分别引入):
compile(project(":spring-aop"))
compile(project(":spring-oxm"))
compile(project(":spring-jdbc"))
compile(project(":spring-aspects"))
compile(project(":spring-context"))
//mysql的链接器:
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.47'
//druid的数据源
compile group: 'com.alibaba', name: 'druid', version: '1.1.10'
//引入切面编程的jar
compile(project(":spring-instrument"))
compile group: 'junit', name: 'junit', version: '4.12'
maven:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.24.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.20.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.21.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
使用注解进行配置:
@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.panzh"})
//@PropertySource("classpath:jdbcTemplate.properties")我们可以采用这种方式来进行注入,这里为了方便起见,就不进行注入了。
public class MainConfig {
//配置DataSource数据源
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
//啥子数据源的名称和密码等等
dataSource.setUsername("root");
dataSource.setPassword("root");
//设置连接的url
dataSource.setUrl("jdbc:mysql://localhost:3306/mysql");
//设置连接的驱动
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
直接在dao层进行调用即可:
@Repository
public class AccountInfoDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public int updateAccountBlance(String accountId,double blance) {
String sql = "update account_info set blance=blance-? where account_id=?";
return jdbcTemplate.update(sql,blance,accountId);
}
public int saveAccountInfo(String accountId,double blance) {
String sql = "insert into account_info(account_id,blance) values(?,?)";
return jdbcTemplate.update(sql,accountId,blance);
}
public double qryBlanceByUserId(String accountId) {
String sql = "select blance from account_info where account_id="+accountId;
return jdbcTemplate.queryForObject(sql, Double.class);
}
}
具体使用方法见参考文档。