• spring整合mybatis


    前期表准备:

    1. create table tbl_account(
    2. id int primary key auto_increment,
    3. name varchar(50) ,
    4. money int
    5. );
    6. insert into tbl_account values (1,'Tom',1000),(2,'Jerry',500);

    一、没使用spring整合mybatis的时候,我们的mybatis写法如下所示:

    程序测试:

    1. import com.itheima.dao.AccountDao;
    2. import com.itheima.domain.Account;
    3. import org.apache.ibatis.io.Resources;
    4. import org.apache.ibatis.session.SqlSession;
    5. import org.apache.ibatis.session.SqlSessionFactory;
    6. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    7. import java.io.IOException;
    8. import java.io.InputStream;
    9. public class App {
    10. public static void main(String[] args) throws IOException {
    11. // 1. 创建SqlSessionFactoryBuilder对象
    12. SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    13. // 2. 加载SqlMapConfig.xml配置文件
    14. InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    15. // 3. 创建SqlSessionFactory对象
    16. SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    17. // 4. 获取SqlSession
    18. SqlSession sqlSession = sqlSessionFactory.openSession();
    19. // 5. 执行SqlSession对象执行查询,获取结果User
    20. AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
    21. Account ac = accountDao.findById(1);
    22. System.out.println(ac);
    23. // 6. 释放资源
    24. sqlSession.close();
    25. }
    26. }

    核心配置文件SqlMapConfig.xml:(以前我们的名字起的是官网形式:mybatis-config.xml)

    新增知识点1:数据库的连接信息可以先写在jdbc.properties文件当中,然后通过 ${#} 符号来获取文件中的属性值

    新增知识点2:当dao/mapper层的代理接口全是通过注解的形式来进行对数据库的增删改查等一些操作的时候,那么我们就可以不再写AccountDao.xml代理接口文件了(在核心配置文件中加载sql映射文件的地方直接加载dao层里的AccountDao类即可访问到该类了,以前我们都是加载到AccountDao.xml)

    1. configuration
    2. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    4. <configuration>
    5. <properties resource="jdbc.properties">properties>
    6. <typeAliases>
    7. <package name="com.itheima.domain"/>
    8. typeAliases>
    9. <environments default="mysql">
    10. <environment id="mysql">
    11. <transactionManager type="JDBC">transactionManager>
    12. <dataSource type="POOLED">
    13. <property name="driver" value="${jdbc.driver}">property>
    14. <property name="url" value="${jdbc.url}">property>
    15. <property name="username" value="${jdbc.username}">property>
    16. <property name="password" value="${jdbc.password}">property>
    17. dataSource>
    18. environment>
    19. environments>
    20. <mappers>
    21. <package name="com.itheima.dao">package>
    22. mappers>
    23. configuration>

    更正:起别名的那个地方是错误的,不是起别名的。

    作用是:因为没有AccountDao代理开发接口的xml文件格式,所以这个 标签的意义是:加载sql映射文件到 AccountDao代理开发接口 通过sql语句查询出来的数据是通过该标签包下的Account类进行封装返回数据的

    dao/mapper层AccountDao:

    1. package com.itheima.dao;
    2. import com.itheima.domain.Account;
    3. import org.apache.ibatis.annotations.Delete;
    4. import org.apache.ibatis.annotations.Insert;
    5. import org.apache.ibatis.annotations.Select;
    6. import org.apache.ibatis.annotations.Update;
    7. import java.util.List;
    8. public interface AccountDao {
    9. @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
    10. void save(Account account);
    11. @Delete("delete from tbl_account where id = #{id} ")
    12. void delete(Integer id);
    13. @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
    14. void update(Account account);
    15. @Select("select * from tbl_account")
    16. List findAll();
    17. @Select("select * from tbl_account where id = #{id} ")
    18. Account findById(Integer id);
    19. }

    jdbc.properties:

     运行结果如下所示:

    二、使用spring整合mybatis

    其实也就是整合mybatis的核心配置文件(如下所示进行整合即可)

     第一步导坐标:

     第二步:既然我们使用spring整合mybatis了(整合的就是mybatis的核心配置文件)那么我们就可以把mybatis的核心配置文件给删除掉了:

     代码演示如下所示:

    App2程序测试类:

    注意:获取IOC容器中被管理的bean的时候我们尽量写接口.class

     如:AccountService accountService =at.getBean(AccountService.class);

    下面我们是用实现接口类的形式,原理是一样的,都是获取被管理的bean

    1. package com.itheima;
    2. import com.itheima.config.SpringConfig;
    3. import com.itheima.domain.Account;
    4. import com.itheima.service.AccountService;
    5. import com.itheima.service.impl.AccountServiceImpl;
    6. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    7. public class App2 {
    8. public static void main(String[] args) {
    9. // 1、获取IOC容器 注意:这个IOC容器名称SpringConfig.class需要参考自己写的
    10. AnnotationConfigApplicationContext at =new AnnotationConfigApplicationContext(SpringConfig.class);
    11. // 2、获取IOC容器中被管理的bean
    12. AccountService accountService =at.getBean(AccountServiceImpl.class);
    13. // 3、调用bean的方法
    14. Account account =accountService.findById(2);
    15. System.out.println(account);
    16. }
    17. }

    java代码代替spring的xml配置文件:

    SpringConfig:

    1. package com.itheima.config;
    2. import org.springframework.context.annotation.ComponentScan;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.context.annotation.Import;
    5. import org.springframework.context.annotation.PropertySource;
    6. /**
    7. * 第二种方式:纯注解开发方式
    8. *
    9. * java代码代替spring的xml配置文件
    10. */
    11. @Configuration // 相当于spring xml配置文件中的总体标签
    12. @ComponentScan("com.itheima") // 扫描该包下是否有注解bean的类,有的话就能取到该类对象了,也就是说有注解bean的类就会被IOC容器给管理了
    13. @PropertySource({"jdbc.properties"}) // 配置加载jdbc.properties文件 使用$符获取数据
    14. @Import({JdbcConfig.class,MybatisConfig.class})
    15. // 导入这两个的目的就是相当于我们没有用spring整合mybatis的时候,mybatis测试程序中“加载核心置
    16. // 文件”的步骤是一样的,这里导入后就说明加载了核心配置文件
    17. public class SpringConfig {
    18. }

     扫描到com.itheima包下的AccountServiceImpl类(该类加了bean注解):

    eg1:那么说明该类就被IOC容器给管理起来了,我们只需要获取到IOC容器,然后拿到IOC容器内被管理的对象,就可以拿到该类

    eg2:该业务逻辑层加上 private AccountDao accountDao; 就和代理接口accountDao产生依赖关系了,就可以调用代理接口中的如增删改查的方法了

    1. package com.itheima.service.impl;
    2. import com.itheima.dao.AccountDao;
    3. import com.itheima.domain.Account;
    4. import com.itheima.service.AccountService;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.List;
    8. @Service // 注解 bean
    9. public class AccountServiceImpl implements AccountService {
    10. @Autowired // 自动装配 处理依赖关系 private AccountDao accountDao = new AccountDao();
    11. /**
    12. * 也就是说:处理完依赖关系后,就相当于这里可以拿到代理接口AccountDao了,然后调用代理接口中的增删改查的方法即可
    13. */
    14. private AccountDao accountDao;
    15. public void save(Account account) {
    16. // 调用代理接口的save方法
    17. // 也就是说,当我们调用AccountService类当中的save()方法后,然后就调用了代理接口的save方法
    18. accountDao.save(account);
    19. }
    20. public void update(Account account){
    21. accountDao.update(account);
    22. }
    23. public void delete(Integer id) {
    24. accountDao.delete(id);
    25. }
    26. public Account findById(Integer id) {
    27. return accountDao.findById(id);
    28. }
    29. public List findAll() {
    30. return accountDao.findAll();
    31. }
    32. }

    业务逻辑层的AccountService接口(该接口写的代码和mapper代理接口其实是一样的):

    eg:业务逻辑层就是做一些相应的逻辑,其实业务逻辑层的接口AccountService的代码和代理接口AccountDao的代码是一样的,只不过有时候会在实现业务层接口AccountServiceImpl的代码上加上了一些逻辑,

    那么你可能会问:为什么业务逻辑层的接口和mapper接口代码一样的话,不直接让实现业务层接口的类直接实现mapper接口呢?

    因为mapper接口有可能会写一些sql注解语句

    1. package com.itheima.service;
    2. import com.itheima.domain.Account;
    3. import java.util.List;
    4. public interface AccountService {
    5. void save(Account account);
    6. void delete(Integer id);
    7. void update(Account account);
    8. List findAll();
    9. Account findById(Integer id);
    10. }

    代理接口AccountDao:

    1. package com.itheima.dao;
    2. import com.itheima.domain.Account;
    3. import org.apache.ibatis.annotations.Delete;
    4. import org.apache.ibatis.annotations.Insert;
    5. import org.apache.ibatis.annotations.Select;
    6. import org.apache.ibatis.annotations.Update;
    7. import java.util.List;
    8. public interface AccountDao {
    9. @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
    10. void save(Account account);
    11. @Delete("delete from tbl_account where id = #{id} ")
    12. void delete(Integer id);
    13. @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
    14. void update(Account account);
    15. @Select("select * from tbl_account")
    16. List findAll();
    17. @Select("select * from tbl_account where id = #{id} ")
    18. Account findById(Integer id);
    19. }

    jdbcConfig:(做mybatis核心配置文件中的连接数据库的操作信息,这里把连接数据库的信息先写在jdbcConfig类当中,然后等会再通过引用类型传给MybatisConfig:专门处理mybatis核心配置文件的类当中

    注意1:如果加载的是properties文件中的数据的话,就需要在SpringConfig类中添加注解@PropertySource({"jdbc.properties"}) // 配置加载jdbc.properties文件

    1. package com.itheima.config;
    2. import com.alibaba.druid.pool.DruidDataSource;
    3. import org.springframework.beans.factory.annotation.Value;
    4. import org.springframework.context.annotation.Bean;
    5. import javax.sql.DataSource;
    6. /**
    7. * 管理第三方jdbc的对象
    8. */
    9. public class JdbcConfig {
    10. /**
    11. * 注解方式完成属性赋值
    12. *
    13. * 注意:这里注解的值是通过获取jdbc.properties文件中获取的,因此别忘记加@PropertySource("#")注解形式
    14. */
    15. @Value("${jdbc.driver}")
    16. private String driver;
    17. @Value("${jdbc.url}")
    18. private String url;
    19. @Value("${jdbc.username}")
    20. private String username;
    21. @Value("${jdbc.password}")
    22. private String password;
    23. /**
    24. * 定义一个方法:用来获取要管理的第三方bean/对象
    25. */
    26. @Bean
    27. public DataSource dataSource(){
    28. // 1、new 第三方bean/对象
    29. DruidDataSource dataSource =new DruidDataSource();
    30. // 2、给第三方bean/对象属性赋值
    31. dataSource.setDriverClassName(driver);
    32. dataSource.setUrl(url);
    33. dataSource.setUsername(username);
    34. dataSource.setPassword(password);
    35. // 3、把第三方bean/对象返回给该方法
    36. return dataSource;
    37. }
    38. }

    MybatisConfig:

    1. package com.itheima.config;
    2. import org.mybatis.spring.SqlSessionFactoryBean;
    3. import org.mybatis.spring.mapper.MapperScannerConfigurer;
    4. import org.springframework.context.annotation.Bean;
    5. import javax.sql.DataSource;
    6. /**
    7. * spring整合mybatis ( 其实也就是整合mybatis的核心配置文件 )
    8. */
    9. public class MybatisConfig {
    10. /*
    11. */
    12. /**
    13. * 该sqlSessionFactory方法new出来的SqlSessionFactoryBean对象相当于整合mybatis的核心配置文件中的上面那些信息
    14. */
    15. @Bean
    16. public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){ // 传参的目的就是处理引用型依赖关系拿到DataSource对象
    17. // 1、new SqlSessionFactoryBean 对象
    18. SqlSessionFactoryBean sqfb =new SqlSessionFactoryBean();
    19. // 2、整合mybatis的核心配置信息
    20. sqfb.setTypeAliasesPackage("com.itheima.domain");
    21. sqfb.setDataSource(dataSource); // 引用型依赖关系为mybatis核心配置文件设置jdbc连接信息
    22. return sqfb;
    23. }
    24. /*
    25. */
    26. /**
    27. * 该mapperScannerConfigurer方法new出来的MapperScannerConfigurer对象相当于整合mybatis的核心配置文件中的上面那些信息
    28. */
    29. @Bean
    30. public MapperScannerConfigurer mapperScannerConfigurer(){
    31. // 1、new MapperScannerConfigurer对象
    32. MapperScannerConfigurer mp =new MapperScannerConfigurer();
    33. // 2、整合mybatis的核心配置信息
    34. mp.setBasePackage("com.itheima.dao");
    35. return mp;
    36. }
    37. }

  • 相关阅读:
    Java学习笔记(十四):String类
    2021年中国环境统计年鉴、工业企业污染排放数据库
    一文讲解ARMv8内存属性与类型(Memory types and attributes)简介
    npm——整理前端包管理工具(cnpm、yarn、pnpm)
    聊聊Android线程优化这件事
    使用jstack工具排查JVM中CPU高消耗问题
    有趣的 Go HttpClient 超时机制
    高级词汇和句子(一)-day30
    怎样下载视频号视频?分享6种有效方法
    【无标题】
  • 原文地址:https://blog.csdn.net/lwj_07/article/details/125865556