今天用spring容器来连接数据库,一直报错。
这是以前的java代码
public class TuserDao extends JdbcTemplate{
public void insert() {
this.update(" insert into STUDENT (stu_id,STUNAME) values (?,?) ", new Object[]{5,"aaa"});
}
}
这是修改之后的代码:
public class TuserDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void insert() {
this.jdbcTemplate.update(" insert into STUDENT (stu_id,STUNAME) values (?,?) ", new Object[]{4,"aaa"});
}
}
前后有什么区别呢?
以前是继承了JdbcTemplate对象,后者是没有继承。
测试类:
@Test
public void aa() {
ApplicationContext context = new
ClassPathXmlApplicationContext("com/etc/spring/jdbc.xml");
TuserService ts = (TuserService) context.getBean("tuserService");
ts.getTuserDao().insert();
}
下面是spring 的 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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 将TuserService类添加到容器中-->
<bean class="com.etc.spring.service.TuserService" id="tuserService">
<property name="tuserDao" ref="tuserDao"></property>
</bean>
<!-- 将TuserDao添加到容器中-->
<bean class="com.etc.spring.dao.TuserDao" id="tuserDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!-- 数据库数据源的配置-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="jdbc:oracle:thin:@192.168.121.132:1521:orcl"/>
<property name="driverClass" value="oracle.jdbc.OracleDriver"/>
<property name="user" value="aa"/>
<property name="password" value="root"/>
<property name="initialPoolSize" value="3"/>
<property name="maxPoolSize" value="10"/>
<property name="minPoolSize" value="1"/>
<property name="acquireIncrement" value="3"/>
<property name="maxIdleTime" value="60"/>
</bean>
<!-- 配置数据源 jdbcTemplate-->
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
如果用继承的方式,那xml的写法和这个是不一样的。