spring是一个非常优秀的轻量级框架,spring的ioc更是解决了代码耦合度的难题,那么如何让jdbcTemplate交给spring管理呢?方法虽然简单,但是这个整合交给spring管理的思想确是一个很大提升
首先写一个bean.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.lwh"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
//配置jdbcTemplate 交给spring容器管理
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
//给dataSource赋值依赖注入
<property name="dataSource" ref="dataSource"></property>
</bean>
//配置数据源
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///spring"></property>
<property name="password" value="root"></property>
<property name="username" value="root"></property>
</bean>
</beans>
然后写一个jdbcTemplateDemo测试类
public class JdbcTemplateDemo {
public static void main(String[] args) {
ApplicationContext ap=new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jt = (JdbcTemplate) ap.getBean("jdbcTemplate");
jt.execute("insert into account1(username,balance)values('dd',1000)");
//spring 自带的封装类
List<Account> accounts1= jt.query("select * from account1 where id >?",new BeanPropertyRowMapper<Account>(Account.class),10);
System.out.println(accounts1.isEmpty()?"kong":accounts1.get(0));
//自己写的封装类
List<Account> accounts= jt.query("select * from account1 where id >?",new AccountRowMappper(),1);
for (Account account:accounts1){
System.out.println(account);
}
}
}
class AccountRowMappper implements RowMapper<Account>{
@Override
//写一个封装account的方法
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account =new Account();
account.setId(resultSet.getInt("id"));
account.setUsername(resultSet.getString("username"));
account.setBalance(resultSet.getDouble("balance"));
return account;
}
}