十、Spring 中的 JdbcTemplate
10.1 概述
JdbcTemplate 是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装。
10.2 准备工作
导入 jar 包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
Account.java
public class Account {
private Integer id;
private String name;
private Float money;
}
JdbcTemplateDemo.java
public static void main(String[] args) {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql:///account");
ds.setUsername("root");
ds.setPassword("1234");
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(ds);
jdbcTemplate.execute("insert into account (name,money) values ('ccc',500)");
}
10.3 使用 Spring 容器创建数据源和 JdbcTemplate
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<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="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
</beans>
JdbcTemplate.java
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
List<Account> list = jt.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
for (Account account : list) {
System.out.println(account);
}
//List<Account> list = jt.query("select * from account", new MyRowMapper());
//for (Account account : list) {
// System.out.println(account);
//}
}
}
// 解决实体的属性和数据库的字段名称不一致的情况
class MyRowMapper implements RowMapper<Account>{
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setId(resultSet.getInt("id"));
account.setName(resultSet.getString("name"));
account.setMoney(resultSet.getFloat("money"));
return account;
}
}