Spring整合Mybatis

集成

1. 引入依赖

  <!--引入相关依赖-->

        <!-- spring jdbc -->

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-jdbc</artifactId>

            <version>${spring.version}</version>

        </dependency>

        <!-- mybatis-->

        <dependency>

            <groupId>org.mybatis</groupId>

            <artifactId>mybatis</artifactId>

            <version>3.4.5</version>

        </dependency>

        <!-- 与spring整合 -->

        <dependency>

            <groupId>org.mybatis</groupId>

            <artifactId>mybatis-spring</artifactId>

            <version>1.3.1</version>

        </dependency>

        <!-- 数据库驱动 -->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <version>8.0.12</version>

        </dependency>

        <!-- 连接池 -->

        <dependency>

            <groupId>com.alibaba</groupId>

            <artifactId>druid</artifactId>

            <version>1.1.7</version>

        </dependency>

2. 添加mybatis的配置

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE configuration

        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <typeAliases>

        <!--几十个实体类-->

        <!--        <typeAlias type="com.tledu.erp.model.User" alias="User"/>-->

        <package name="com.tledu.model"/>

    </typeAliases>

    <mappers>

        <package name="com.tledu.erp.mapper"/>

    </mappers>

</configuration>

3. 添加数据库配置

4. 配置spring配置文件

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       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">

    <!--配置扫描注解-->

    <context:annotation-config/>

    <!--告诉spring,要扫描com.tledu包下面的注解-->

    <context:component-scan base-package="com.tledu"/>

    <!--开启切面支持-->

    <aop:aspectj-autoproxy/>

    <!-- 1) 读取properties中的内容-->

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 2) 数据库连接池 -->

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

        <property name="driverClassName" value="${jdbc.driver}"/>

        <property name="url" value="${jdbc.url}"/>

        <property name="username" value="${jdbc.username}"/>

        <property name="password" value="${jdbc.password}"/>

        <property name="maxActive" value="${jdbc.max}"/>

        <property name="minIdle" value="${jdbc.min}"/>

    </bean>

    <!-- 3) 获取 SqlSessionFactory 工厂类-->

    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="dataSource"/>

        <property name="configLocation" value="classpath:mybatis-config.xml" />

    </bean>

    <!-- 4) 搜索有哪些 mapper 实现类,把mapper接口自动配置成 spring 中的 <bean>-->

    <bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <!-- name="basePackage":(起始)包名, 从这个包开始扫描-->

        <property name="basePackage" value="com.tledu.mapper"/>

    </bean>

</beans>

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")

事务

添加依赖

   <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-tx</artifactId>

            <version>${spring.version}</version>

        </dependency>

增加配置

 <!-- 使使用注解配置的事务行为生效 -->

    <tx:annotation-driven transaction-manager="txManager"/><!-- 仍然需要一个PlatformTransactionManager -->

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <!-- (这个需要的对象是在其他地方定义的) -->

        <property name="dataSource" ref="dataSource"/>

    </bean>

使用注解

    @Transactional(rollbackFor = Exception.class)

    public int insert(User user) {

        // 根据数据做一些处理

        userDao2.insert(user);

        addressMapper.insert(new Address());

        throw new RuntimeException();

    }

流程:

  1. 增加事务的配置
  2. 添加事务的注解
    1. rollbackFor:回滚的时机
    2. 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的依赖

<dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-jdbc</artifactId>

<version>${spring.version}</version>

</dependency>

1.3.2 配置文件

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       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">

    <!--配置扫描注解-->

    <context:annotation-config/>

    <!--告诉spring,要扫描com.tledu包下面的注解-->

    <context:component-scan base-package="com.tledu"/>

    <!--加上aop的约束-->

    <aop:aspectj-autoproxy/>

  

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 数据库连接池 -->

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

        <property name="driverClassName" value="${jdbc.driver}"/>

        <property name="url" value="${jdbc.url}"/>

        <property name="username" value="${jdbc.username}"/>

        <property name="password" value="${jdbc.password}"/>

        <!--最大连接数-->

        <property name="maxActive" value="${jdbc.max}"/>

        <!--初始空闲池的个数-->

        <property name="minIdle" value="${jdbc.min}"/>

    </bean>

</beans>

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

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       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">

    <!--配置扫描注解-->

    <context:annotation-config/>

    <!--告诉spring,要扫描com.tledu包下面的注解-->

    <context:component-scan base-package="com.tledu"/>

    <!--加上aop的约束-->

    <aop:aspectj-autoproxy/>

  

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 数据库连接池 -->

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

        <property name="driverClassName" value="${jdbc.driver}"/>

        <property name="url" value="${jdbc.url}"/>

        <property name="username" value="${jdbc.username}"/>

        <property name="password" value="${jdbc.password}"/>

        <!--最大连接数-->

        <property name="maxActive" value="${jdbc.max}"/>

        <!--初始空闲池的个数-->

        <property name="minIdle" value="${jdbc.min}"/>

    </bean>

      <!-- 配置一个数据库的操作模板:JdbcTemplate -->

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

        <property name="dataSource" ref="dataSource" />

    </bean>

</beans>

1.4.3 基本使用1

/*

 * JdbcTemplate的最基本用法

 */

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

/**

 * JdbcTemplate的最基本用法

 */

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 增删改查

 

/**

 * JdbcTemplate的CRUD操作

 */

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<Account> accounts = jt.query(

                            "select * from account where money > ?",

                            new AccountRowMapper(), 1000f);

              accounts = jt.query("select * from account where money > ?",

                            new BeanPropertyRowMapper<Account>(Account.class), 1000f);

              for (Account account : accounts) {

                     System.out.println(account);

              }

              // 查询一个

              accounts = jt.query("select * from account where id = ?",

                            new BeanPropertyRowMapper<Account>(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);

       }

}

 

/**

 * 定义Account的封装策略

 */

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;

       }

}

1.5 Dao中使用jdbcTemplate

1.5.1 实体类

packagecom.tledu.zrz.spring.model;

importjava.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 +

                '}';

    }

}

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<Account> accounts = jdbcTemplate.query("select * from account where id = ?",newBeanPropertyRowMapper<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 = ?",newBeanPropertyRowMapper<Account>(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;

 

/**

 * JdbcTemplate的最基本用法

 */

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<Account> accounts = super.getJdbcTemplate().query(

                                   "select * from account where id = ?",

                                   newBeanPropertyRowMapper<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 = ?",

                                   newBeanPropertyRowMapper<Account>(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 配置文件

<?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.tledu.zrz.spring.dao.impl.AccountDaoImpl">

         <!-- <property name="jdbcTemplate" ref="jdbcTemplate"></property> -->

                  <!-- 注入 dataSource -->

                  <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.jdbc.Driver"></property>

                  <property name="url" value="jdbc:mysql://localhost:3306/test"></property>

                  <property name="username" value="root"></property>

                  <property name="password" value="root"></property>

         </bean>

</beans>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值