http://blog.youkuaiyun.com/Trigl/article/details/50934675?locationNum=1&fps=1
1 配置数据源
Spring并没有提供数据源连接池实现,但是apache的DBCP是一个不错 选择,DBCP包含了多个提供连接池功能的数据源,其中BasicDataSource是最常使用的,在XML中的配置如下:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
<property name="username" value="KFDB" />
<property name="password" value="KFDB" />
<property name="initialSize" value="1" />
<property name="maxActive" value="50" />
<property name="maxIdle" value="5" />
<property name="minIdle" value="15" />
<property name="maxWait" value="10000" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="10000" />
</bean>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
2 使用SimpleJdbcTemplate访问数据库
在DAO层装配SimpleJdbcTemplate
package com.trigl.springjdbc;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
public class UserDao1 {
private SimpleJdbcTemplate jdbcTemplate;
public void setJdbcTemplate(SimpleJdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private static final String SQL_INSERT_USER ="insert into jdbc_test (user_id, name, password, realname, email) values (seq_user.nextval, ?, ?, ?, ?)";
public void addUser(User user) {
jdbcTemplate.update(SQL_INSERT_USER, user.getUsername(), user.getPassword(),user.getRealName(),user.getEmail());
System.out.println("新增用户成功!用户信息为:" + user);
}
}
注意这里必须有setter方法,因为装配bean就是通过setter方法实现的。
XML中配置SimpleJdbcTemplate
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<bean id="userDao1" class="com.trigl.springjdbc.UserDao1">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
测试类
package com.trigl.springjdbc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
publicclassUserDao1Test
{
publicstaticvoidmain(String[]
args) {
ApplicationContext ctx =new
ClassPathXmlApplicationContext("config/bean.xml");
UserDao1 userDao1 = (UserDao1)ctx.getBean("userDao1");
User user =new
User("Trigl","123456","白鑫","18810690994@163.com");
userDao1.addUser(user);
}
}