Spring Boot 2.x基础教程:使用MyBatis的XML配置方式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring Boot 2.x基础教程:使用MyBatis的XML配置方式

程序猿DD   2020-03-09 我要评论
[上一篇](http://blog.didispace.com/spring-boot-learning-21-3-5/)我们介绍了如何在Spring Boot中整合我们国人最常用的MyBatis来实现对关系型数据库的访问。但是上一篇中使用了注解方式来实现,而对于很多MyBatis老用户还是习惯于XML的开发方式,所以这篇,我们就来看看如何使用XML的方式来进行开发。 ## 动手试试 本篇将不具体介绍整合MyBatis的基础内容,读者可以阅读[上一篇:Spring Boot 2.x基础教程:使用MyBatis访问MySQL](http://blog.didispace.com/spring-boot-learning-21-3-5/)来了解该部分内容。 下面的实操部分将基于上一篇的例子之后进行,基础工程可通过文末仓库中的`chapter3-5`目录获取。 **第一步**:在应用主类中增加mapper的扫描包配置: ```java @MapperScan("com.didispace.chapter36.mapper") @SpringBootApplication public class Chapter36Application { public static void main(String[] args) { SpringApplication.run(Chapter36Application.class, args); } } ``` **第二步**:在第一步中指定的Mapper包下创建User表的Mapper定义: ```java public interface UserMapper { User findByName(@Param("name") String name); int insert(@Param("name") String name, @Param("age") Integer age); } ``` **第三步**:在配置文件中通过`mybatis.mapper-locations`参数指定xml配置的位置: ```properties mybatis.mapper-locations=classpath:mapper/*.xml ``` **第四步**:在第三步中指定的xml配置目录下创建User表的mapper配置: ```xml ``` 到这里从注解方式的MyBatis使用方式就改为了XML的配置方式了,为了验证是否运行正常,可以通过下面的单元测试来尝试对数据库的写和读操作: ```java @Slf4j @RunWith(SpringRunner.class) @SpringBootTest @Transactional public class Chapter36ApplicationTests { @Autowired private UserMapper userMapper; @Test @Rollback public void test() throws Exception { userMapper.insert("AAA", 20); User u = userMapper.findByName("AAA"); Assert.assertEquals(20, u.getAge().intValue()); } } ``` 如果您在尝试没有成功,建议通过文末仓库查看完成代码,对比是否有所遗漏与疏忽。 **更多本系列免费教程连载[「点击进入汇总目录」](http://blog.didispace.com/spring-boot-learning-2x/)** ## 代码示例 本文的相关例子可以查看下面仓库中的`chapter3-6`目录: - Github:[https://github.comhttps://img.qb5200.com/download-x/dyc87112/SpringBoot-Learning/](https://github.comhttps://img.qb5200.com/download-x/dyc87112/SpringBoot-Learning/tree/master/2.1.x) - Gitee:[https://gitee.comhttps://img.qb5200.com/download-x/didispace/SpringBoot-Learning/](https://gitee.comhttps://img.qb5200.com/download-x/didispace/SpringBoot-Learning/tree/master/2.1.x) **如果您觉得本文不错,欢迎`Star`支持,您的关注是我坚持的动力!**

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们