麻绳先生

做一些记录性的工作

spring中的JdbctTemplate

是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装,spring框架提供了许多操作模板类。

  • 操作关系型数据
    • JdbcTemplate
    • HibernateTemplate
  • 操作nosql数据库
    • RedisTemplate
  • 操作消息队列
    • JmsTemplate

JdbcTemplate作用

和数据库交互的模板类

JdbcTemplate基本用法

首先通过XML文件配置必要信息,这块是spring框架必要的IOC手法;

1
2
3
4
5
6
7
8
9
10
11
<!--配置JdbcTemplate-->
<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://localhost:3306/databasename"></property>
<property name="username" value="username"></property>
<property name="password" value="password"></property>
</bean>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//获取对象
JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
//执行操作
jt.execute("insert into account(name, money) values ('name', 222)");
//保存
jt.update("insert into account(name, money) values (?, ?)", "name", 333);
//更新
jt.update("update account set name=?, money=?, where id=?","test",2345,3);
//删除
jt.update("delete from account where id=?", 3);
//查询所有
List<Account> accounts = jt.query("select * from account where money > ?", new AccountRowMapper(), 1000f);
List<Account> accounts = jt.query("select * from account where money > ?", new BeanPropertyRowMapper<Account>(Account.class), 1000f);
for(Account account : accounts){
System.out.println(account);
}
//查询一个
List<Account> accounts = jt.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), 1);
//查询返回一行一列(使用聚合函数,但是不加group by子句
Long count = jt.queryForObject("select count(*) from account where money > ?", Long.class, 1000f);