1、JdbcTemplate
spring对数据库的操作在jdbc上做了更深层次的封装JdbcTemplate
,处理了资源的建立和释放(不需要我们管理连接了),我们只需要提供SQL语句(不需要我们设置参数了)和提取结果(查询时候可以直接返回对应的实体类),使JDBC更加易于使用。它也可以使用spring的注入功能,将数据源注入JdbcTemplate
,来实现操作数据库。
2、JdbcTemplate常用方法
- update(更新数据)
- batchUpdate(批量更新数据)
- queryForObject(查询单行数据或者单值数据)
- query(查询多行数据)
3、Spring中实现jdbcTemplate对数据库操作(采用c3p0连接池)
1、需要导入的jar包
- spring-jdbc-5.0.6.RELEASE.jar
- spring-tx-5.0.6.RELEASE.jar
- mysql-connector-java-5.0.7.jar
- c3p0-0.9.5.2.jar
2、springxml配置
<context:property-placeholder
location="classpath:jdbc.properties" />
<!-- 配置c3p0数据源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
</bean>
<!-- 将c3p0数据源注入jdbcTemplate -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
3、User实体类
public class User {
private int id;
private String username;
private String password;
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
4、测试类
public void testUserServiceImpl() {
//获取IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//通过ApplicationContext对象的getBean方法来获取对象实例
//获取数据连接模板JdbcTemplate
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
//增加
String sql1 = "insert into user(username,password) values(?,?)";
System.out.println(jdbcTemplate.update(sql1, "user","user123"));
//修改
String sql2 = "update user set username = ? where id = 10000";
System.out.println(jdbcTemplate.update(sql2, "adminadmin"));
//查询基本数据
String sql3 = "select count(*) from user";
System.out.println(jdbcTemplate.queryForObject(sql3, Integer.class));
//查询单条记录
String sql4 = "select * from user where id = 10000";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
User user = jdbcTemplate.queryForObject(sql4, rowMapper);
System.out.println(user);
//查询多条记录
String sql5 = "select * from user";
List<User> list = jdbcTemplate.query(sql5, rowMapper);
for (User user2 : list) {
System.out.println(user2);
}
//批量插入
String sql6 = "insert into user(username,password) values(?,?)";
List<Object[]> batchArgs=new ArrayList<Object[]>();
batchArgs.add(new Object[]{"aaaa","aaa123"});
batchArgs.add(new Object[]{"bbbb","bbb123"});
batchArgs.add(new Object[]{"cccc","ccc123"});
jdbcTemplate.batchUpdate(sql6, batchArgs);
}