★学习目标:
掌握Spring和Mybatis整合,能够在项目中进行Spring和MyBatis的整合操作
★思考任务:
1、自述ssm框架基础结构搭建的步骤?
★任务学习:
视频学习
★知识要点:
Spring和MyBatis的整合步骤
Spring和MyBatis的整合可以分为2步来完成,首先搭建Spring环境,然后整合MyBatis到Spring环境中。框架环境包含框架对应的依赖和配置文件,其中Spring的依赖、MyBatis的依赖、Spring和MyBatis整合的依赖,在项目基础结构搭建时候已经引入到项目中了,接下来,只需编写Spring的配置文件、Spring和MyBatis整合的配置文件即可。
1.Spring的配置文件创建配置文件application-service.xml,用于配置Spring对Service层的扫描信息。application-service.xml具体代码如下所示。<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"...><!--开启注解扫描, 扫描包--><context:component-scan base-package="com.itheima.service"/></beans>
2.Spring和MyBatis整合的配置
Spring和MyBatis的整合包中提供了一个SqlSessionFactoryBean对象,该对象的Bean需要注入数据源,也可以根据需求在SqlSessionFactoryBean的Bean中配置MyBatis核心文件路径、别名映射和Mapper映射文件路径。创建数据源属性文件jdbc.properties,jdbc.properties配置的数据源信息如下所示。jdbc.driverClassName=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaijdbc.username=rootjdbc.password=rootyx.ityxb.comyx.ityxb.com
整合测试
创建名称为BookServiceTest的测试类,用于对Spring和MyBatis的整合进行测试。@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:application-service.xml", "classpath:application-dao.xml"})public class BookServiceTest {@Autowired private BookService bookService;@Testpublic void findBookById() {Book book = bookService.findBookById(1);// 输出语句输出:图书id、图书名称、作者、出版社,省略}}
结果测试

运行测试方法findBookById(),方法运行后控制台打印信息如图所示。从图中所示的信息可以看出,程序打印出了id为1的图书信息。这表明测试类中成功装配了BookService对象,BookService对象成功调用Service层的findBookById()方法,Service层的findBookById()方法成功调用Dao层的findBookById()方法完成了数据查询。说明Spring和MyBatis已经整合成功。

