Spring 整合 Mybatis -- Spring入门(七)

文章介绍了Mybatis的一般开发流程,包括数据库表设计、实体类创建、配置文件编写、Mapper接口及注解使用。接着分析了Spring整合Mybatis的思路,强调了SqlSessionFactory的核心作用。然后详细阐述了Spring环境下Mybatis的整合步骤,包括Spring配置、数据源设置、Mapper扫描等。最后,提供了整合后的测试类和项目文件结构。


前言

为了巩固所学的知识,作者尝试着开始发布一些学习笔记类的博客,方便日后回顾。当然,如果能帮到一些萌新进行新技术的学习那也是极好的。作者菜菜一枚,文章中如果有记录错误,欢迎读者朋友们批评指正。
(博客的参考源码可以在我主页的资源里找到,如果在学习的过程中有什么疑问欢迎大家在评论区向我提出)

发现宝藏

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。【宝藏入口】。

一、Mybatis一般开发流程

1. 设计创建数据库表tbl_account

  • 建表查询语句示例
create database spring_db;
use spring_db;

drop table if exists tbl_account;

create table tbl_account(
	id int primary key auto_increment,
	name varchar(20),
	account varchar(20)
);

INSERT INTO tbl_account VALUES (1, 'Tom', 1000);
INSERT INTO tbl_account VALUES (2, 'Jerry', 500);

  • 效果

在这里插入图片描述

2. 创建对应maven模块并在pom.xml导入对应坐标

 <dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.6</version>
 </dependency>

 <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
 </dependency>

3. 创建对应实体类Account

public class Account implements Serializable {
    //此处省略getter、setter和toString方法
    private Integer id;
    private String name;
    private Double money;
    
}

4. 创建mybatis核心配置文件mybatis-config.xml

<?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>
    <properties resource="jdbc.properties"></properties>
    
    <typeAliases>
        <package name="com.itheima.domain"/>
    </typeAliases>
    
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <package name="org.example.dao"></package>
    </mappers>
</configuration>

5. 创建数据库表信息jdbc.properties

 jdbc.driver=com.mysql.jdbc.Driver
 jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
 jdbc.username=root
 jdbc.password=root
 

6. 用注解的方式创建编写mappper代理接口AccountDao(或者是一个接口对应一个mapper文件)

public interface AccountDao {

    @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
    void save(Account account);

    @Delete("delete from tbl_account where id = #{id} ")
    void delete(Integer id);

    @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
    void update(Account account);

    @Select("select * from tbl_account")
    List<Account> findAll();

    @Select("select * from tbl_account where id = #{id} ")
    Account findById(Integer id);
}

7. 创建模拟测试类APP

public class App {
    public static void main(String[] args) throws IOException {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 3. 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        // 4. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 5. 执行SqlSession对象执行查询,获取结果User
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);

        Account ac = accountDao.findById(1);
        System.out.println(ac);

        // 6. 释放资源
        sqlSession.close();
    }
}

  1. 模拟测试类运行结果

在这里插入图片描述

9. 文件结构参考

在这里插入图片描述

二、spring整合mybatis思路分析

1. 我们知道spring的特点之一就是能管理bean,那mybatis中有哪些bean是需要交给spring去管理的呢?我们可以将mybatis的示例运行程序APP分为以下几个部分,通过观察我们可以发现主要有如下几个对象:SqlSessionFactorySqlSessionAccountDao

在这里插入图片描述

  • 虽然AccountDao是直接执行业务的,但是它不是根源上的对象,而且随着业务需求不同,造出来的对象也不一样,所以它不是最核心的对象。
  • SqlSession对象是由工厂造出来的,类似于连接池,该对象实际已经造好
  • 所以最核心的对象是SqlSessionFactory

2. 通过观察Mybatis的核心配置文件我们可以将其分为如下几个部分:

在这里插入图片描述

  • 第一部分 的作用是配置加载数据库信息,有没有的区别是加载的信息是否在本配置文件获取,与SqlSessionFactory没什么关系
  • 第二部分 的作用是配置Mybatis操作完后得到的数据是什么类型,是SqlSessionFactory对象中可选的一个属性
  • 第三部分 dataSourcre 标签中的部分是数据库连接信息,是必须的,如果没有该内容,SqlSessionFactory无法获知操作的数据库信息
  • 第三部分 transactionManager 标签中的部分是事务处理相关内容,与SqlSessionFactory也有关系,本博客暂时不做探讨
  • 第四部分 是业务操作相关的,即使没有,SqlSessionFactory也能创建。但是在实际开发中,如果需要用到Mapper代理开发,就需要配置这部分内容。

3. 小结

综上考虑,spring要重点管理的mybatis中的核心对象是 SqlSessionFactory,用Spring创建出SqlSessionFactory对象和业务相关的 Mapper映射对象是我们的主要目标。

三、Spring整合Mybatis环境准备(注解开发)

  1. 在pom.xml文件中导入spring开发相关坐标
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.16</version>
    </dependency>

<!--spring操作数据库-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

<!--spring整合mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

2. 创建Spring核心配置类SpringConfig

 @Configuration
 @ComponentScan("org.example")

 public class SpringConfig {
 }

3. 创建业务接口AccountService

public interface AccountService {

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List<Account> findAll();

    Account findById(Integer id);

}

4. 创建对应的实现类AccountServiceImpl

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public void save(Account account) {
        accountDao.save(account);
    }

    public void update(Account account){
        accountDao.update(account);
    }

    public void delete(Integer id) {
        accountDao.delete(id);
    }

    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    public List<Account> findAll() {
        return accountDao.findAll();
    }
}

5. 数据库连接信息

  • 创建数据库信息配置类JdbcConfig
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}
  • 加载数据库信息properties文件
@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
}

  • 加载数据库信息配置类

方式一:在核心配置类上加@Configuration,通过Spring核心配置类SpringConfig中的@ComponentScan注解扫描

方式二:手工导入

@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
@Import(JdbcConfig.class)
public class SpringConfig {
}

6. 文件结构预览

在这里插入图片描述

四、Spring整合Mybatis

1. MybatisConfig配置类

  • 创建Mybatis配置类MybatisConfig(实现目标:创建SqlSessionFactoryBean)
public class MybatisConfig {
    //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        //设置别名
        ssfb.setTypeAliasesPackage("org.example.domain");
        //配置数据源
        ssfb.setDataSource(dataSource);
        return ssfb;
    }

    //定义bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("org.example.dao");
        return msc;
    }

}




  • 加载Mybatis配置类
@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}

2. 创建模拟测试类

public class App2 {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        AccountService accountService = ctx.getBean(AccountService.class);

        Account ac = accountService.findById(1);
        System.out.println(ac);
    }
}

3. 运行结果

在这里插入图片描述
4. 文件结构预览

在这里插入图片描述

五、小结

简单来说,Spring整合Mybatis就是在Spring开发的基础上多了一个MyBatisConfig配置文件

在这里插入图片描述
在这里插入图片描述

`博客内容借鉴了bilibili黑马程序员SSM课程资料`

总结

欢迎各位留言交流以及批评指正,如果文章对您有帮助或者觉得作者写的还不错可以点一下关注,点赞,收藏支持一下。
(博客的参考源码可以在我主页的资源里找到,如果在学习的过程中有什么疑问欢迎大家在评论区向我提出)

评论 154
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东离与糖宝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值