集成
1. 引入依赖
spring-jdbc
mybatis
mybatis-spring
mysql-connector-java
druid
2. 添加mybatis的配置
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
3. 添加数据库配置
4. 配置spring配置文件
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
6. 创建mapper
1. 引入依赖
2. 配置mybatis
3. 配置spring,在spring中集成mybatis
3.1 读取jdbc配置文件
3.2 配置druid数据库连接池
3.3 配置sqlSessionFactory
3.4 配置mapper扫描
4. 可以通过注入的方式使用mapper
4.1 Service没有起名字
4.2 警告useSSL=false
4.3 一直连接不上()
4.4. 为了知道连接不上的原因,添加日志配置
4.5 原因是时区问题,在url中添加时区的配置
通过注解的方式扫描mapper可以通过@MapperScan("com.tledu.spring_mybatis.mapper")
事务
添加依赖
spring-tx
增加配置
使用注解
@Transactional(rollbackFor = Exception.class)
public int insert(User user) {
// 根据数据做一些处理
userDao2.insert(user);
addressMapper.insert(new Address());
throw new RuntimeException();
}
流程:
- 增加事务的配置
- 添加事务的注解
- rollbackFor:回滚的时机
- isolation:隔离级别
jdbcTemplate
1.1 概述
它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。spring 框架为我们提供了很多的操作模板类。
操作关系型数据的:
JdbcTemplate
HibernateTemplate
操作 nosql 数据库的:
RedisTemplate
操作消息队列的:
JmsTemplate
我们今天的主角在spring-jdbc.jar 中,我们在导包的时候,除了要导入这个 jar 包 外,还需要导入一个 spring-tx.jar(它是和事务相关的)。
1.2 jdbcTemplate对象创建
我们可以参考它的源码,来一探究竟:
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
setDataSource(dataSource);
setLazyInit(lazyInit);
afterPropertiesSet();
}
除了默认构造函数之外,都需要提供一个数据源。既然有set方法,依据我们之前学过的依赖注入,我们可以在配置文件中配置这些对象
1.3 配置数据源
1.3.1 环境搭建
增加jdbc的依赖
spring-jdbc
1.3.2 配置文件
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
1.4 增删改查
1.4.1 示例数据
创建表:
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci
INSERT INTO `test`.`account` (`id`, `name`, `money`) VALUES ('1', '张三', '99');
INSERT INTO `test`.`account` (`id`, `name`, `money`) VALUES ('2', '李四', '89');
INSERT INTO `test`.`account` (`id`, `name`, `money`) VALUES ('3', '王五', '15645600');
1.4.2 配置jdbcTemplate
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
1.4.3 基本使用1
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
//准备数据源:spring的内置数据源
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/test");
ds.setUsername("root");
ds.setPassword("root");
//1.创建JdbcTemplate对象
JdbcTemplate jt = new JdbcTemplate();
//给jt设置数据源
jt.setDataSource(ds);
//2.执行操作
jt.execute("insert into account(name,money)values('ccc',1000)");
}
}
1.4.4 基本使用2
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
//3.执行操作
jt.execute("insert into account(name,money)values('ddd',2222)");
}
}
1.4.5 增删改查
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
// 1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.获取对象
JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
// 3.执行操作
// 保存
jt.update("insert into account(name,money)values(?,?)", "eee", 3333f);
// 更新
jt.update("update account set name=?,money=? where id=?", "test", 4567,
7);
// 删除
jt.update("delete from account where id=?", 8);
// 查询所有
List accounts = jt.query(
"select * from account where money > ?",
new AccountRowMapper(), 1000f);
accounts = jt.query("select * from account where money > ?",
new BeanPropertyRowMapper(Account.class), 1000f);
for (Account account : accounts) {
System.out.println(account);
}
// 查询一个
accounts = jt.query("select * from account where id = ?",
new BeanPropertyRowMapper(Account.class), 1);
System.out.println(accounts.isEmpty() ? "没有内容" : accounts.get(0));
// 查询返回一行一列(使用聚合函数,但不加group by子句)
Long count = jt.queryForObject(
"select count(*) from account where money > ?", Long.class,
1000f);
System.out.println(count);
}
}
class AccountRowMapper implements RowMapper {
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 +
'}';
}
}
1.5.2 持久化层接口
packagecom.tledu.zrz.spring.dao;
importcom.tledu.zrz.spring.model.Account;
public interface IAccountDao {
unt findAccountById(Integer accountId);
Account findAccountByName(String accountName);
voidupdateAccount(Account account);
}
1.5.3 第一种:dao定义jdbcTemplate
1.5.3.1 实现类
packagecom.tledu.zrz.spring.dao.impl;
importorg.springframework.jdbc.core.BeanPropertyRowMapper;
importorg.springframework.jdbc.core.JdbcTemplate;
importcom.tledu.zrz.spring.dao.IAccountDao;
importcom.tledu.zrz.spring.model.Account;
importjava.util.List;
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public voidsetJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Account findAccountById(Integer accountId) {
List accounts = jdbcTemplate.query("select * from account where id = ?",newBeanPropertyRowMapper(Account.class),accountId);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account findAccountByName(String accountName) {
List accounts = jdbcTemplate.query("select * from account where name = ?",newBeanPropertyRowMapper(Account.class),accountName);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw newRuntimeException("结果集不唯一");
}
return accounts.get(0);
}
@Override
public voidupdateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
1.5.3.3 测试
package com.tledu.zrz.spring.jdbctemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tledu.zrz.spring.dao.IAccountDao;
import com.tledu.zrz.spring.model.Account;
public class JdbcTemplateDemo4 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
IAccountDao accountDao = ac.getBean("accountDao",IAccountDao.class);
Account account = accountDao.findAccountById(1);
System.out.println(account);
account.setMoney(30000f);
accountDao.updateAccount(account);
}
}
1.5.4 第二种:继承JdbcDaoSupport
JdbcDaoSupport 是 spring 框架为我们提供的一个类,该类中定义了一个 JdbcTemplate 对象,我们可以直接获取使用,但是要想创建该对象,需要为其提供一个数据源:
具体源码如下:
public abstract class JdbcDaoSupport extends DaoSupport {
//定义对象
private JdbcTemplate jdbcTemplate;
//set 方法注入数据源,判断是否注入了,注入了就创建 JdbcTemplate
public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
//如果提供了数据源就创建 JdbcTemplate
this.jdbcTemplate = createJdbcTemplate(dataSource);
initTemplateConfig();
}
}
//使用数据源创建 JdcbTemplate
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
//当然,我们也可以通过注入 JdbcTemplate 对象
public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
initTemplateConfig();
}
//使用getJdbcTmeplate 方法获取操作模板对象
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
1.5.4.1 实现类
packagecom.tledu.zrz.spring.dao.impl;
importorg.springframework.jdbc.core.BeanPropertyRowMapper;
importorg.springframework.jdbc.core.support.JdbcDaoSupport;
importcom.tledu.zrz.spring.dao.IAccountDao;
importcom.tledu.zrz.spring.model.Account;
importjava.util.List;
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer accountId) {
List accounts = super.getJdbcTemplate().query(
"select * from account where id = ?",
newBeanPropertyRowMapper(Account.class), accountId);
return accounts.isEmpty() ? null : accounts.get(0);
}
@Override
public Account findAccountByName(String accountName) {
Listaccounts = super.getJdbcTemplate().query(
"select * from account where name = ?",
newBeanPropertyRowMapper(Account.class), accountName);
if (accounts.isEmpty()) {
return null;
}
if (accounts.size() > 1) {
throw newRuntimeException("结果集不唯一");
}
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());
}
}
1.5.4.2 配置文件
"1.0"encoding="UTF-8"?>
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">
class="org.springframework.jdbc.datasource.DriverManagerDataSource">



