Spring对jdbc的支持
2024-10-20 20:57:11
Spring对jdbc技术提供了很好的支持。
体现在:
1)Spring对c3p连接池的支持很完善;
2)Spring对jdbc提供了JdbcTemplate,来简化jdbc操作;
1.使用步骤
1)引入jar文件
spring-jdbc-3.2.5.RELEASE.jar
spring-tx-3.2.5.RELEASE.jar
c3p0连接池包
数据库驱动包
2) 容器创建DataSource对象
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///student"/>
<property name="user" value="root"/>
<property name="password" value="juaner767"/>
<property name="initialPoolSize" value="3"/>
<property name="maxPoolSize" value="6"/>
<property name="maxStatements" value="100"/>
<property name="acquireIncrement" value="2"/>
</bean>
<bean id="userDao" class="com.juaner.spring.jdbc.UserDao">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
3)使用连接池对象
public class UserDao {
//注入datasorce
private DataSource dataSource; public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
} public void save() {
String sql = "insert into student values( 4,'李四')";
Connection conn = null;
PreparedStatement stmt = null; try {
conn = dataSource.getConnection();
stmt = conn.prepareStatement(sql);
stmt.executeUpdate();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.使用JdbcTemplate优化
public void save() {
String sql = "insert into student(name) values( '李四')";
//使用spring优化
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql);
}
封装一个对象
String sql1 = "select * from student";
List<Student> query = jdbcTemplate.query(sql1, new RowMapper<Student>() {
//如何封装一行记录
@Override
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
Student student = new Student();
student.setId(resultSet.getInt("id"));
student.setName(resultSet.getString("name"));
return student;
}
});
容器创建JdbcTemplate
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
<bean id="userDao" class="com.juaner.spring.jdbc.UserDao">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
最新文章
- [转载]Python-第三方库requests详解
- 解决Sharepoint 2010 custom display form 不显示附件的问题
- PATH路径出错导致任何命令都找不到解决方法
- Python-S13作业-day4-之登陆,管理后台
- python list删除元素 del remove
- HotSwap和JRebel原理
- 将TIBCO Host 实例注册为Windows服务
- iLearning D3.js 2.0 released
- Easyui弹出窗体在iframe的父级页面显示
- clip原理
- ORM武器:NHibernate(三)五个步骤+简单对象CRUD+HQL
- 浅谈MySQL分表
- scala 小结(一)
- Kafka配置项unclean.leader.election.enable造成consumer出现offset重置现象
- 《剑指offer》-找到字符串中第一个只出现一个的字符
- zabbix使用percona插件监控mysql
- 各种开源协议介绍 BSD、Apache Licence、GPL V2 、GPL V3 、LGPL、MIT_转
- css定位问题的记录
- 解题:POI 2012 Cloakroom
- LeetCode765. Couples Holding Hands