文章目录
1. JdbcTemplate对象
- JdbcTemplated是Spring提供的一个连接数据库的org.springframework.jdbc.core.JdbcTemplate
- dbutils.QueryRunner是dbutils包提供的一个连接数据库
- 两者类似。
2. 由JdbcTemplate对象自己提供的数据库
- JdbcTemplate中的DriverManagerDataSource可以准备数据源;
- execute方法执行SQL语句,直接把参数值写死,不用占位符?。
JdbcTemplateDemo1
package com.jh.jdbctemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**JdbcTemplate的最基本用法*/
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
//准备数据源
DriverManagerDataSource ds=new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/maven?serverTimezone=GMT%2B8");
ds.setUsername("root");
ds.setPassword("jh7851192");
//1.创建JdbcTemplate对象
JdbcTemplate jt = new JdbcTemplate();
//给jt设置数据源
jt.setDataSource(ds);
//2.执行操作
jt.execute("insert into account(name,money)values ('ccc',1200)");
}
}
3.JdbcTemplate采用XML配置的方法配置数据库
不用像JdbcTemplateDemo1一样把数据库写死
JdbcTemplateDemo2
package com.jh.jdbctemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**JdbcTemplate的最基本用法
* 采用XML配置的方法配置数据源,不用像JdbcTemplateDemo1一样把数据库写死
* */
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//2.获取bean对象JdbcTemplate
JdbcTemplate jt=ac.getBean("jdbcTemplate",JdbcTemplate.class);
//3.执行操作
//execute 没有占位符?,直接写参数值
jt.execute("insert into account(name,money)values ('ddd',2200)");
}
}
bean.xml
- 这里也是配置数据源class="org.springframework.jdbc.datasource.DriverManagerDataSource
- 只是把DriverManagerDataSource写到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="accountDao" class="com.jh.dao.impl.AccountDaoImpl">
<!--注入JdbcTemplate对象-->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
<!--<property name="dataSource" ref="dataSource"></property>-->
</bean>
<!--配置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.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/maven?serverTimezone=GMT%2B8"></property>
<property name="username" value="root"></property>
<property name="password" value="jh7851192"></property>
</bean>
</beans>
4. JdbcTemplate对象 CRUD操作(数据库xml已配置)
- 执行操作(这里写占位符? 和QueryRunner(query,update)一样,但是和execute方法不一样)
- Spring提供一个BeanPropertyRowMapper,类似于dbutils.QueryRunner中的BeanListHandler,BeanHandler
JdbcTemplateDemo3
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//2.获取bean对象JdbcTemplate
JdbcTemplate jt=ac.getBean("jdbcTemplate",JdbcTemplate.class);
//3.执行操作(这里写占位符? 和QueryRunner(query,update)一样,但是和execute方法不一样)
/*//保存
jt.update("insert into account(name,money)values (?,?)","eee",2345f);
//更新
jt.update("update account set name=?,money=? where id=?","jh2",2324f,6);
//删除
jt.update("delete from account where id=?",6);*/
//查询所有
//List<Account>accounts = jt.query("select * from account where money > ?",new AccountRowMapper(),1000f);
/**Spring提供一个BeanPropertyRowMapper,类似于dbutils.QueryRunner中的BeanListHandler,BeanHandler
* 以后不用自己写实现类:class AccountRowMapper*/
/*List<Account>accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),1000f);
for (Account account:accounts){
System.out.println(account);
Account{id=1, name='aaa', money=4566.0}
Account{id=5, name='jh', money=12213.0}
Account{id=7, name='ddd', money=2200.0}
}*/
//查询一个
List<Account> accounts = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);
System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));
//Account{id=1, name='aaa', money=4566.0}
//查询返回一行一列(使用聚合函数,但不加group by子句)
Long count = jt.queryForObject("select count(*) from account where money >?", Long.class, 1000f);
System.out.println(count);//3
}
}
//这是自己写的类AccountRowMapper
class AccountRowMapper implements RowMapper<Account>{
/**
* 把结果集中的数据封装到Account中,然后由Spring把每个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;
}
}
5. 将SQL语句写在持久层
- 通过获取IAccountDao的bean对象,已在bean.xml里逐步注入对象,进行调用,实现数据库的调用;
- accountDao—>jdbcTemplate—>dataSource
JdbcTemplateDemo4
public class JdbcTemplateDemo4 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//2.获取bean对象
IAccountDao accountDao=ac.getBean("accountDao",IAccountDao.class);
//3.执行操作
Account account = accountDao.findAccountById(2);
System.out.println(account);//Account{id=1, name='aaa', money=4566.0}
account.setMoney(1200f);
accountDao.updateAccount(account);//下一次就更新为Account{id=1, name='aaa', money=1230.0}
}
}
Account
package com.jh.domain;
import java.io.Serializable;
/**账户的实体类*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
IAccountDao
package com.jh.dao;
import com.jh.domain.Account;
/**持久层*/
public interface IAccountDao {
//根据id查询账户
Account findAccountById(Integer accountId);
//根据名称查询账户
Account findAccountByName(String accountName);
//更新账户
void updateAccount(Account account);
}
SQL语句在持久层实现类写
package com.jh.dao.impl;
import com.jh.dao.IAccountDao;
import com.jh.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**持久层实现类*/
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
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);
}
@Override
public Account findAccountByName(String accountName) {
List<Account> accounts = jdbcTemplate.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) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
抽取重复代码:可以省略private JdbcTemplate jdbcTemplate;和set方法
extends JdbcDaoSupport
package com.jh.dao.impl;
import com.jh.dao.IAccountDao;
import com.jh.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
/**持久层实现类
*抽取重复代码:可以省略private JdbcTemplate jdbcTemplate;和set方法
* */
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
@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());
}
}