–学习资料来自于黑马公开课程–
Spring jdbcTemplate基本使用
1.1 jdbcTemplate概述
它是Spring框架中提供的一个对象,是原始繁琐的jdbc API的简单封装。
spring框架提供了多种操作模板类:
- 操作关系型数据的jdbcTemplate
- 操作nosql数据库的RedisTemplate
- 操作消息队列的JmsTemplate
1.2 jdbcTemplate开发步骤
- 导入spring-jdbc和spring-tx坐标
- 创建数据库表和实体
- 创建jdbcTemplate对象
- 执行数据库操作
2快速入门
- 在pom.xml文件中导入相关坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
- 创建account数据表和Account实体
public class Account {
private String name;
private double money;
public String getName() {
return name;
}
public double getMoney() {
return money;
}
public void setName(String name) {
this.name = name;
}
public void setMoney(double money) {
this.money = money;
}
}
- 创建Template对象并执行数据库操作
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setUser("123");
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
jdbcTemplate.update("insert into account values (?,?)","tom",500);
执行完成就可以看到数据库有数据插入啦。
3. Spring框架下的jdbcTemplate使用姿势
将jdbcTemplate交给Spring管理
- 在xml文件中完成datasource和jdbcTemplate Bean的配置
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
<property name="user" value="root"></property>
<property name="password" value="123"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestJdbcTemplate {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
public void insert(){
jdbcTemplate.update("insert into account values (?,?)","MOT",1000);
}
@Test
public void delete(){
jdbcTemplate.update("delete from account where name=?","MOT");
}
@Test
public void update(){
jdbcTemplate.update("update account set name=? where name=?","NewTom","tom");
}
@Test
public void queryAll(){
List<Account> accounts = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
for (Account a: accounts) {
System.out.println(a.getName()+":"+a.getMoney());
}
}
@Test
public void queryCount(){
Integer num = jdbcTemplate.queryForObject("select count(*) from account",Integer.class);
System.out.println(num);
}
}
JdbcTemplate提供的方法还有很多,笔记也只是跟着老师的笔记敲一敲