ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

【Spring教程12】Spring框架实战:Spring整合Mybatis全面深入详解

【Spring教程12】Spring框架实战:Spring整合Mybatis全面深入详解 目录*1 Spring整合Mybatis思路分析* * 1.1 环境准备 * * 1.1.1 步骤1:准备数据库表 * 1.1.2 步骤2:创建项目导入jar包 * 1.1.3 步骤3:根据表创建模型类 * 1.1.4 步骤4:创建Dao接口 * 1.1.6 步骤6:添加jdbc.properties文件 * 1.1.7 步骤7:添加Mybatis核心配置文件 * 1.1.8 步骤8:编写应用程序 * 1.1.9 步骤9:运行程序 * 1.2 整合思路分析* 2 Spring整合Mybatis* * 2.1 步骤1:项目中导入整合需要的jar包 * 2.2 步骤2:创建Spring的主配置类 * 2.3 步骤3:创建数据源的配置类 * 2.4 步骤4:主配置类中读properties并引入数据源配置类 * 2.5 步骤5:创建Mybatis配置类并配置SqlSessionFactory * 2.6 步骤6:主配置类中引入Mybatis配置类 * 2.7 步骤7:编写运行类 * 2.8 步骤8:运行程序 欢迎大家回到《 Java教程之Spring30天快速入门》本教程所有示例均基于Maven实现如果您对Maven还很陌生请移步本人的博文《 如何在windows11下安装Maven并配置以及 IDEA配置Maven环境》本文的上一篇为《 IOC/DI注解开发管理第三方bean》学习到这里已经对Spring有一个简单的认识了Spring有一个容器叫做IoC容器里面保存bean。在进行企业级开发的时候其实除了将自己写的类让Spring管理之外还有一部分重要的工作就是使用第三方的技术。前面已经讲了如何管理第三方bean了下面结合IoC和DI整合Mybatis进一步加深对Spring的使用理解。1 Spring整合Mybatis思路分析---------------------### 1.1 环境准备在准备环境的过程中我们也来回顾下Mybatis开发的相关内容:#### 1.1.1 步骤1:准备数据库表Mybatis是来操作数据库表所以先创建一个数据库及表 create database spring_db character set utf8; use spring_db; create table tbl_account( id int primary key auto_increment, name varchar(35), money double ); #### 1.1.2 步骤2:创建项目导入jar包项目的pom.xml添加相关依赖 org.springframework spring-context 5.2.10.RELEASE com.alibaba druid 1.1.16 org.mybatis mybatis 3.5.6 mysql mysql-connector-java 5.1.47 #### 1.1.3 步骤3:根据表创建模型类 public class Account implements Serializable { private Integer id; private String name; private Double money; //setter…getter…toString…方法略 } #### 1.1.4 步骤4:创建Dao接口 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 findAll(); Select(“select * from tbl_account where id #{id} “) Account findById(Integer id); } 1.1.5 步骤5:创建Service接口和实现类 public interface AccountService { void save(Account account); void delete(Integer id); void update(Account account); List findAll(); Account findById(Integer id); } 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 findAll() { return accountDao.findAll(); } } #### 1.1.6 步骤6:添加jdbc.properties文件resources目录下添加用于配置数据库连接四要素 jdbc.drivercom.mysql.jdbc.Driver jdbc.urljdbc:mysql://localhost:3306/spring_db?useSSLfalse jdbc.usernameroot jdbc.passwordroot useSSL:关闭MySQL的SSL连接#### 1.1.7 步骤7:添加Mybatis核心配置文件 ?xml version1.0 encodingUTF-8? #### 1.1.8 步骤8:编写应用程序 public class App { public static void main(String[] args) throws IOException { // 1. 创建SqlSessionFactoryBuilder对象 SqlSessionFactoryBuilder sqlSessionFactoryBuilder new SqlSessionFactoryBuilder(); // 2. 加载SqlMapConfig.xml配置文件 InputStream inputStream Resources.getResourceAsStream(“SqlMapConfig.xml.bak”); // 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.1.9 步骤9:运行程序### 1.2 整合思路分析Mybatis的基础环境我们已经准备好了接下来就得分析下在上述的内容中哪些对象可以交给Spring来管理* Mybatis程序核心对象分析从图中可以获取到真正需要交给Spring管理的是SqlSessionFactory* 整合Mybatis就是将Mybatis用到的内容交给Spring管理分析下配置文件说明:* 第一行读取外部properties配置文件Spring有提供具体的解决方案PropertySource ,需要交给Spring * 第二行起别名包扫描为SqlSessionFactory服务的需要交给Spring 第三行主要用于做连接池Spring之前我们已经整合了Druid连接池这块也需要交给Spring * 前面三行一起都是为了创建SqlSession对象用的那么用Spring管理SqlSession对象吗回忆下SqlSession是由SqlSessionFactory创建出来的所以只需要将SqlSessionFactory交给Spring管理即可。 * 第四行是Mapper接口和映射文件[如果使用注解就没有该映射文件]这个是在获取到SqlSession以后执行具体操作的时候用所以它和SqlSessionFactory创建的时机都不在同一个时间可能需要单独管理。2 Spring整合Mybatis-----------------前面我们已经分析了Spring与Mybatis的整合大体需要做两件事 第一件事是:Spring要管理MyBatis中的SqlSessionFactory 第二件事是:Spring要管理Mapper接口的扫描 具体该如何实现具体的步骤为:### 2.1 步骤1:项目中导入整合需要的jar包 org.springframework spring-jdbc 5.2.10.RELEASE org.mybatis mybatis-spring 1.3.0 ### 2.2 步骤2:创建Spring的主配置类 //配置类注解 Configuration //包扫描主要扫描的是项目中的AccountServiceImpl类 ComponentScan(“com.itheima”) public class SpringConfig { } ### 2.3 步骤3:创建数据源的配置类在配置类中完成数据源的创建 public class JdbcConfig { Value(”j d b c . d r i v e r ) p r i v a t e S t r i n g d r i v e r ; V a l u e ( {jdbc.driver}) private String driver; Value(jdbc.driver)privateStringdriver;Value({jdbc.url}”) private String url; Value(”j d b c . u s e r n a m e ) p r i v a t e S t r i n g u s e r N a m e ; V a l u e ( {jdbc.username}) private String userName; Value(jdbc.username)privateStringuserName;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; } } ### 2.4 步骤4:主配置类中读properties并引入数据源配置类 Configuration ComponentScan(“com.itheima”) PropertySource(“classpath:jdbc.properties”) Import(JdbcConfig.class) public class SpringConfig { } ### 2.5 步骤5:创建Mybatis配置类并配置SqlSessionFactory public class MybatisConfig { //定义beanSqlSessionFactoryBean用于产生SqlSessionFactory对象 Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) { SqlSessionFactoryBean ssfb new SqlSessionFactoryBean(); //设置模型类的别名扫描 ssfb.setTypeAliasesPackage(“com.itheima.domain”); //设置数据源 ssfb.setDataSource(dataSource); return ssfb; } //定义bean返回MapperScannerConfigurer对象 Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer msc new MapperScannerConfigurer(); msc.setBasePackage(“com.itheima.dao”); return msc; } }说明:* 使用SqlSessionFactoryBean封装SqlSessionFactory需要的环境信息* SqlSessionFactoryBean是前面我们讲解FactoryBean的一个子类在该类中将SqlSessionFactory的创建进行了封装简化对象的创建我们只需要将其需要的内容设置即可。 * 方法中有一个参数为dataSource,当前Spring容器中已经创建了Druid数据源类型刚好是DataSource类型此时在初始化SqlSessionFactoryBean这个对象的时候发现需要使用DataSource对象而容器中刚好有这么一个对象就自动加载了DruidDataSource对象。* 使用MapperScannerConfigurer加载Dao接口创建代理对象保存到IOC容器中* 这个MapperScannerConfigurer对象也是MyBatis提供的专用于整合的jar包中的类用来处理原始配置文件中的mappers相关配置加载数据层的Mapper接口类 * MapperScannerConfigurer有一个核心属性basePackage就是用来设置所扫描的包路径 ### 2.6 步骤6:主配置类中引入Mybatis配置类 Configuration ComponentScan(“com.itheima”) PropertySource(“classpath:jdbc.properties”) Import({JdbcConfig.class,MybatisConfig.class}) public class SpringConfig { } ### 2.7 步骤7:编写运行类在运行类中从IOC容器中获取Service对象调用方法获取结果 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); } } ### 2.8 步骤8:运行程序支持Spring与Mybatis的整合就已经完成了其中主要用到的两个类分别是:* SqlSessionFactoryBean* MapperScannerConfigurer
返回列表