JdbcTemplate是Spring框架中提供的一个对象,对原始的JDBC API进行简单封装,其用法与
DBUtils`类似.
<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/eesy">
property>
<property name="username" value="root">
property>
<property name="password" value="root">
property>
bean>
public static void main(String[] args) {
//1 获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jt=ac.getBean("JdbcTemplate",JdbcTemplate.class);
jt.execute("insert into account(name,money)values('eeee',1000)");
//保存
jt.update("insert into account(name,money) values(?,?)","eeee",333);
//更新
jt.update("update account set name=?,money=? where id=?","eeee",4567,7);
//删除
jt.update("delect from account where id=?",8);
与DBUtils十分类似,JdbcTemplate的查询操作使用其query()方法,其参数如下:
String sql: SQL语句
RowMapper rowMapper: 指定如何将查询结果ResultSet对象转换为T对象.
@Nullable Object… args: SQL语句的参数
其中RowMapper类类似于DBUtils的ResultSetHandler类,可以自己写一个实现类,但常用Spring框架内置的实现类BeanPropertyRowMapper(T.class)
//自己写的类AccountRoMapper()
//List accounts=jt.query("select * from account where money=?",new AccountRoMapper(),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);
}
//查询一个
public Account findAccountById(Integer accountId) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
return accounts.isEmpty() ? null : accounts.get(0);
}
class AccountRoMapper implements RowMapper<Account>{
/*把结果集中的数据封装到Account
*/
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account =new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account;
}
聚合查询
JdbcTemplate
中执行聚合查询的方法为queryForObject()
方法,其参数如下:
String sql
: SQL语句Class requiredType
: 返回类型的字节码@Nullable Object... args
: SQL语句的参数public static void main(String[] args) {
//1.获取Spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取JdbcTemplate对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.聚合查询
Integer total = jt.queryForObject("select count(*) from account where money > ?", Integer.class, 500);
System.out.println(total);
}
在每个DAO层直接加入JdbcTemplate的话,如果要有很多个DAO,那么每个里面都需要加,那样代码就会变得冗余。为了抽取代码,我们可以建立一个JdbcDaoSupport类用于抽取重复代码。然后再DAO的实现类中继承。在JdbcDaoSupport
类中定义了JdbcTemplate
和DataSource
成员属性,在实际编程中,只需要向其注入DataSource
成员即可,DataSource
的set方法中会注入JdbcTemplate
对象.
public class JdbcDaoSupport {
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource=dataSource;
if(jdbcTemplate==null){
jdbcTemplate=creteJdbcTemplate(dataSource);
}
}
public JdbcTemplate creteJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}
目前Spring中有内置的JdbcDaoSupport,所以我们可以不写具体的类,直接继承Spring中的类
在实现DAO接口时,我们通过super.getJdbcTemplate()
方法获得JdbcTemplate
对象.
@Override
public Account findAccountById(Integer accountid) {
List<Account> accounts=super.getJdbcTemplate().query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),accountid);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account findAccountByName(String accountName) {
List<Account> accounts=super.getJdbcTemplate().query("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}