博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring-boot-mybatis-demo
阅读量:2430 次
发布时间:2019-05-10

本文共 2138 字,大约阅读时间需要 7 分钟。

简要说明

spring-boot建议orm采用JPA,因为jpa符合spring-boot简化配置理念。但是最近在使用jpa的过程中各种不爽,特别是多表联合查询的时候,也可能是我对jpa还没深入。由于个人经历,mybatis使用较多,现整合spring-boot和mybatis。

按照约定,其实spring-boot整合mybatis非常简单,只需要加一个mybatis.mapper-locations配置项标明mybatis的xml映射文件在哪,mybatis接口加上@Mapper注解告诉spring的bean工厂,这是mybatis的mapper接口即可。

引入依赖包

pom.xml

mysql
mysql-connector-java
${mysql-connector.version}
org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis-spring-boot.version}

添加配置

application.properties

mybatis.mapper-locations=classpath:mapper/*.xml

该配置指明mybatis的xml映射文件位置。

添加mapper注解

@Mapper

@Mapperpublic interface CityBeanMapper {
long countByExample(CityBeanExample example); int deleteByExample(CityBeanExample example); int deleteByPrimaryKey(Short cityId); int insert(CityBean record); int insertSelective(CityBean record); List
selectByExample(CityBeanExample example); CityBean selectByPrimaryKey(Short cityId); int updateByExampleSelective(@Param("record") CityBean record, @Param("example") CityBeanExample example); int updateByExample(@Param("record") CityBean record, @Param("example") CityBeanExample example); int updateByPrimaryKeySelective(CityBean record); int updateByPrimaryKey(CityBean record);}

mybatis接口层添加@Mapper注解,告诉spring的上下文管理器,自动把该接口实例化,并纳入spring上下文管理器中,以后使用的时候便可自动注入到需要的类中。

Server层使用

@Service(value = "cityService")public class CityServiceImpl implements CityService {
@Autowired private CityBeanMapper cityBeanMapper; @Transactional public Boolean save(CityBean cityBean) { if (null == cityBean.getCityId()) { return cityBeanMapper.insert(cityBean)>0?true:false; }else{ return cityBeanMapper.updateByPrimaryKey(cityBean)>0?true:false; } } public CityBean findById(Short id) { return cityBeanMapper.selectByPrimaryKey(i); }}

自动生成

使用mybatis的时候很多时候都是通过mybatis-generator自动生成mapper.xml、接口、model。示例工程中已经加入了相关的配置,可参考。


工程地址:

原文地址:

转载地址:http://puvmb.baihongyu.com/

你可能感兴趣的文章
和 Java、C# 等语言对比后,Python 简直酷上天了!
查看>>
程序媛到最后,拼的到底是什么?
查看>>
笑死!996 程序员竟然做了这个梦!| 每日趣闻
查看>>
“再见,微软!”
查看>>
ARM 发布新一代 CPU 和 GPU,实现 20% 性能提升!
查看>>
技术引路:机器学习仍大有可为,但方向在哪里?
查看>>
漫画:如何给女朋友解释什么是编译与反编译
查看>>
刷屏了!这篇 Python 学习贴,90% 的程序员都用的上!
查看>>
漫画:如何给女朋友解释什么是适配器模式?
查看>>
程序员又迎来一个好消息! | 每日趣闻
查看>>
Mac 被曝存在恶意漏洞:黑客可随意调动摄像头,波及四百万用户!
查看>>
拒绝与其他码农一致!CSDN定制T让你成为最靓的仔
查看>>
程序员情商低?看完这 4 类程序员我懂了!
查看>>
《长安十二时辰》里你不能不知道的 IT 技术 | 每日趣闻
查看>>
程序员爬取 3 万条评论,《长安十二时辰》槽点大揭秘!
查看>>
一年参加一次就够,全新升级的 AI 开发者大会议程出炉!
查看>>
基于 XDanmuku 的 Android 性能优化实战
查看>>
基于嵌入式操作系统的物联网安全
查看>>
一个只有 99 行代码的 JS 流程框架
查看>>
移动周刊第 186 期:移动 App 客户端性能优化、iOS 开源库源码解析
查看>>