1.结构图
2.(方法一:基础使用模板)
2.1实体类:Account
package com.itheima.pojo;
//Serializable数据序列化
import java.io.Serializable;
public class Account implements Serializable {
private int id;
private String name;
private Float money;
public int getId() {
return id;
}
public void setId(int 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 +
'}';
}
}
2.2 创建一个类 templateJdbcDemo1(使用第一个类来实现sql+数据源配置)
package com.itheima.template;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class templateJdbcDemo1 {
/*创建一个对象*/
public static void main(String[] args) {
//3.没有数据源:今天介绍的是spring的内置数据源
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc.mysql://localhost:3306/eesy");
ds.setUsername("root");
ds.setPassword("123456");
//1.创建jdbcTemplate对象
JdbcTemplate jt = new JdbcTemplate();
//4.给jt设置数据源
jt.setDataSource(ds);
//2.执行操作
jt.execute("insert into account(name,money)value('ccc',1000)");
}
}
2.3、使用spring管理的模版配置数据源(使用第二个类来实现main(sql)+bean(datasource))
package com.itheima.template;
import com.itheima.pojo.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.xml.transform.Templates;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class templateJdbcDemo2 {
public static void main(String[] args) {
/*使用spring容器管理:TemplateJdbc:CRUT的操作*/
//1.获取容器
ApplicationContext as = new ClassPathXmlApplicationContext("bean.xml");
//2.使用模版
JdbcTemplate ts = (JdbcTemplate) as.getBean("jdbcTemplate");
//3.操作
//插入一条
/*ts.execute("insert into account(name,money)value('zhou',10000000)");*/
//保存
/*ts.update("insert into account(name ,money) value(?,?)","eee",3333);*/
//更新
/*ts.update("update account set name=?,money=? where id=?","test",4576,3);*/
//删除
/*ts.update("delete from account where id=?",5);*/
//查询所有(调用接口执行)
// 1.封装类型
/*List<Account> accounts = ts.query("select * from account where money>?",new AccountRowMapper(),10000);*/
/*2.使用spring容器自带的BeanPropertyRowMapper*/
/*List<Account> accounts = ts.query("select * from account where money>?",new BeanPropertyRowMapper<Account>(Account.class),10000);
for (Account account:accounts) {
System.out.println(account);//查询所有
}*/
//查询一个
/*List<Account> accounts = ts.query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),6);
System.out.println(accounts.isEmpty()?"没有查询到":accounts.get(0));//二元运算符*/
//查询一个返回一行一列(使用聚合函数,但不加group by子句)
Long count = ts.queryForObject("select count(*) from account where money > ?",Long.class,1000);
System.out.println("一共有"+count+"行");
}
}
//定义Accouont的封装策略: 1.封装类型——>2.调用接口执行
// 方法二:使用spring自带的BeanPropertyRowMapper<Account>(Account.class)来解决,但是如果没有这样直接使用的时候,就只能用自己写接口
/*
class AccountRowMapper implements RowMapper<Account>{
/* 把结果集中的对象封装的Account中,然后由spring把每个Account加到集合中* /
@Override
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;
}
}*/
bean.xml
<!-- 配置数据源 -->
<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?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
2.4、使用Dao持久层来使用JdbcTempla模版(Dao(sql)+bean(datasource))
创建持久层接口IAccountDao
package com.itheima.dao;
import com.itheima.pojo.Account;
//账号持久层的实现类接口
public interface IAccountDao {
//根据Id查询账户
Account findAccountById(Integer accountId);
//根据名称查询账户
Account findAccountByName(String accountName);
//更新账户
void updateAccount(Account account);
}
创建实现类AccountDaoImp
package com.itheima.dao.imp;
import com.itheima.dao.IAccountDao;
import com.itheima.pojo.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
//持久层的实现类
@Autowired
private JdbcTemplate jdbcTemplate;
public class AccountDaoImpl1 implements IAccountDao {
//按id查询(return accounts.isEmpty()?null:accounts.get(0);id的结果只有一个,查来查去只有一个,所以能使用这种方法)
@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方法 ;优化得出:
package com.itheima.dao.imp;
import com.itheima.dao.IAccountDao;
import com.itheima.pojo.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
//持久层的实现类(extends基于XML的方式,就选择这样的)
public class AccountDaoImpl1 extends JdbcDaoSupport implements IAccountDao {
//按id查询(return accounts.isEmpty()?null:accounts.get(0);id的结果只有一个,查来查去只有一个,所以能使用这种方法)
@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);*/
//第二种抽取代码块之后
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 = jdbcTemplate.query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),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) {
/*jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());*/
//使用第二种方法:抽取代码块
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
/*jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());*/
}
}
新编写一个类JdbcDaoSupport:重复的代码写入
package com.itheima.dao.imp;
import com.itheima.dao.IAccountDao;
import com.itheima.pojo.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.util.List;
//抽取重复的代码块
public class JdbcDaoSupport{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
private DataSource dataSource;
public void setDataSource(DataSource dataSource){
this.dataSource = dataSource;
if (jdbcTemplate == null){
jdbcTemplate = createJdbcTemplate(dataSource);
}
}
private JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}====》可无明白抽取思想即可,spring中自带的有支持包
创建实现类表现层templateJdbcDemo3(dao外写sql方法:main直接调用)
package com.itheima.template;
import com.itheima.dao.IAccountDao;
import com.itheima.pojo.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class templateJdbcDemo3 {
public static void main(String[] args) {
/*使用spring容器管理:TemplateJdbc:CRUT的操作*/
//1.获取容器
ApplicationContext as = new ClassPathXmlApplicationContext("bean.xml");
//2.使用bean配置的模版(接口实现)
IAccountDao accountDao = as.getBean("accountDao",IAccountDao.class);
//3.使用模版进行操作:根据id查找
/*Account account = accountDao.findAccountById(4);
System.out.println("account="+account);*/
//3.2使用模版进行操作:根据name查找
/*Account account = accountDao.findAccountByName("test");
System.out.println("account:"+account);*/
//3.3使用模版进行操作:更新一条
Account account = accountDao.findAccountById(4);
account.setName("hhhhh");
account.setMoney(10000000f);
accountDao.updateAccount(account);
}
}
持续优化之后:spring继承的时候有这个JdbcDaoSupport类【import org.springframework.jdbc.core.support.JdbcDaoSupport;】直接使用,已经不需要自己写:但是如果没有类似的但是以后开发项目的时候,代码重复多了可以,就使用抽取代码块的思想。
完整的为:
1.IAccountDao
2.AccountDaoImpl2
package com.itheima.dao.imp;
import com.itheima.dao.IAccountDao;
import com.itheima.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import java.util.List;
//持久层的实现类(基于注解的就选择这样的)
@Repository
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
@Autowired
private JdbcTemplate 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());
}
}
3.bean.xml(accountDao)
<?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">
<!--配置持久层dbcTemplate模版-->
<bean id="accountDao" class="com.itheima.dao.imp.AccountDaoImpl1">
<!--注入jdbcTemplate模版-->
<property name="jdbcTemplate" ref="jdbcTemplate"></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.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
但是,抽取代码块只是适用于基于XML的开发(set注入),如果是基于注解的话就抽取不了,这里需要注意。
总结:
JdbcTemplate模版
1.创建对象来配置数据源(sql操作也在main中)
2.通过spring容器来管理(通过spring容器来管理数据源,main负责操作sql)
3.通过使用Dao接口来进行操作sql,使用在main直接调用就好(Dao(sql)+bean(datasource)+ main调用dao方法就行)
知识还很浅薄,道路尚还长远,加油