MyBatis 是一款标准的 ORM 框架,被广泛的应用于各企业开发中。具体细节这里就不在叙述,大家自行查找资料进行学习下。

加载依赖

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>

application 配置(application.yml)

mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.zhb.entity
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
password: root
username: root

启动类

在启动类中添加对 Mapper 包扫描@MapperScan,Spring Boot 启动的时候会自动加载包路径下的 Mapper。

@Spring BootApplication
@MapperScan("com.zhb.mapper")
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

或者直接在 Mapper 类上面添加注解@Mapper,建议使用上面那种,不然每个 Mapper 加个注解会很麻烦。

代码展示

这里只说下,我们在controller 中 尽量使用 Restful 风格

@RestController
public class UserController { @Resource
private UserMapper userMapper; @GetMapping(value = "/users")
public List<UserEntity> getUsers() {
List<UserEntity> users=userMapper.getAll();
return users;
} @GetMapping(value = "/users/{id}")
public UserEntity getUser(@PathVariable(value = "id") Long id) {
UserEntity user=userMapper.getOne(id);
return user;
} @PostMapping("/users")
public void save(UserEntity user) {
userMapper.insert(user);
} @PutMapping("/users")
public void update(UserEntity user) {
userMapper.update(user);
} @DeleteMapping(value="/users/{id}")
public void delete(@PathVariable("id") Long id) {
userMapper.delete(id);
} }

实际开发常遇问题

在平常开发中,我们经常会遇到返回树结构,如下展示

[
{
"id": "1",
"name": "山东",
"pid": "0",
"children": [
{
"id": "2",
"name": "济南",
"pid": "1",
"children": [
{
"id": "3",
"name": "高新区",
"pid": "2",
"children": null
}
]
}
]
}
]
(1) java中 通过对list数据进行拼接成树

如下面的方法(这里直接声明了list,往里面添加数据,来演示查询出的list集合)

@GetMapping(value = "/area")
public List<AreaTreeEntity> get(){ List<AreaTreeEntity> res= new ArrayList<>();
Map<String,List<AreaTreeEntity>> childMap = new HashMap<>(16); //为了方便测试,构建list数据
List<AreaTreeEntity> s = new ArrayList<>();
AreaTreeEntity a = new AreaTreeEntity();
a.setId("1");
a.setName("山东");
a.setPid("0");
s.add(a); AreaTreeEntity a1 = new AreaTreeEntity();
a1.setId("2");
a1.setName("济南");
a1.setPid("1");
s.add(a1); AreaTreeEntity a2 = new AreaTreeEntity();
a2.setId("3");
a2.setName("高新区");
a2.setPid("2");
s.add(a2); for(AreaTreeEntity entity : s){ if ("0".equals(entity.getPid())) { res.add(entity);
}
else { List<AreaTreeEntity> childList = (childMap.containsKey(entity.getPid())) ? childMap.get(entity.getPid()) : new ArrayList<>();
childList.add(entity); if (!childMap.containsKey(entity.getPid())){
childMap.put(entity.getPid(),childList);
}
}
} for(AreaTreeEntity entity : res){
findChild(entity,childMap);
} return res;
} public void findChild(AreaTreeEntity entity,Map<String,List<AreaTreeEntity>> childMap){ if (childMap.containsKey(entity.getId())){
List<AreaTreeEntity> chidList = childMap.get(entity.getId());
for (AreaTreeEntity childEntity : chidList){
findChild(childEntity,childMap);
}
entity.setChildren(chidList);
}
}

经过验证,返回数据如下

[
{
"id": "1",
"name": "山东",
"pid": "0",
"children": [
{
"id": "2",
"name": "济南",
"pid": "1",
"children": [
{
"id": "3",
"name": "高新区",
"pid": "2",
"children": null
}
]
}
]
}
]
(2) 使用mabatis的collection 直接查询出树结构

<mapper namespace="com.zhb.mapper.AreaTreeMapper" >
<resultMap id="TreeResultMap" type="com.zhb.entity.AreaTreeEntity" >
<result column="id" property="id" jdbcType="VARCHAR" />
<result column="name" property="name" jdbcType="VARCHAR" />
<collection property="children" column="id" ofType="com.zhb.entity.AreaTreeEntity" javaType="ArrayList" select="selectChildrenById"/>
</resultMap> <select id="getAreaTree" resultMap="TreeResultMap">
select id,name from area where parent_id = '0'
</select> <select id="selectChildrenById" parameterType="java.lang.String" resultMap="TreeResultMap">
select id,name from area where parent_id = #{id}
</select> </mapper>

完整代码下载:github

注:项目中加入swagger ,方便大家测试,直接访问 http://localhost:8080/swagger-ui.html

SpringBoot(九)_springboot集成 MyBatis的更多相关文章

  1. SpringBoot系列之集成Mybatis教程

    SpringBoot系列之集成Mybatis教程 环境准备:IDEA + maven 本博客通过例子的方式,介绍Springboot集成Mybatis的两种方法,一种是通过注解实现,一种是通过xml的 ...

  2. SpringBoot学习之集成mybatis

    一.spring boot集成Mybatis gradle配置: //gradle配置: compile("org.springframework.boot:spring-boot-star ...

  3. SpringBoot(十)_springboot集成Redis

    Redis 介绍 Redis是一款开源的使用ANSI C语言编写.遵守BSD协议.支持网络.可基于内存也可持久化的日志型.Key-Value高性能数据库. 数据模型 Redis 数据模型不仅与关系数据 ...

  4. SpringBoot(八)_springboot集成swagger2

    swagger是一个功能强大的api框架,它的集成非常简单,不仅提供了在线文档的查阅,而且还提供了在线文档的测试. (1) 引入依赖,我们选择现在最新的版本 <dependency> &l ...

  5. springboot 零xml集成mybatis

    maven依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  6. springboot之集成mybatis mongo shiro druid redis jsp

    闲来无事,研究一下spingboot  发现好多地方都不一样了,第一个就是官方默认不支持jsp  于是开始狂找资料  终于让我找到了 首先引入依赖如下: <!-- tomcat的支持.--> ...

  7. springboot集成mybatis(二)

    上篇文章<springboot集成mybatis(一)>介绍了SpringBoot集成MyBatis注解版.本文还是使用上篇中的案例,咱们换个姿势来一遍^_^ 二.MyBatis配置版(X ...

  8. springboot集成mybatis(一)

    MyBatis简介 MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyB ...

  9. SpringBoot 集成Mybatis 连接Mysql数据库

    记录SpringBoot 集成Mybatis 连接数据库 防止后面忘记 1.添加Mybatis和Mysql依赖 <dependency> <groupId>org.mybati ...

随机推荐

  1. springboot之rabbitmq

    一.RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件).RabbitMQ服务器是用Erlang语言编写的,而集群和故障转移是构建在开放电信平台框架上的.所有 ...

  2. angular 服务 service factory provider constant value

    angular服务 服务是对公共代码的抽象,由于依赖注入的要求,服务都是单例的,这样我们才能到处注入它们,而不用去管理它们的生命周期. angular的服务有以下几种类型: 常量(Constant): ...

  3. yum 出现error: db5 error

    yum 安装k8s的过程中用了 Ctrl+ z, 然后yum 再也不能使用了: Error: rpmdb open failed 解决方法: rpm --rebuilddb yum clean all ...

  4. 新手入门之——Ubuntu上的编辑器之神Vi / Vim

    Ubuntu上的编辑器有gedit.vi.sublime等.gedit一般在没有其他编辑器时临时使用,大部分情况下,vi和sublime使用的比较多,Linux系统内置了vi和sublime,其中,s ...

  5. 报错:Cannot create PoolableConnectionFactory (The server time zone value 'CST' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverT

    报错:Cannot create PoolableConnectionFactory (The server time zone value 'CST' is unrecognized or repr ...

  6. pandas安装以及出现的问题

    pandas安装以及出现的问题 1.pandas 安装 pandas是Python的第三方库,所以使用前需要安装一下,直接使用pip install pandas就会自动安装,安装成功后显示的以下的信 ...

  7. NO--13微信小程序,左右联动

    写在前面: 从2016年张小龙发布微信小程序这种新的形态,到2017年小程序的不温不火,再到今年小程序的大爆发,从一度刷爆朋友圈的‘头脑王者’,再到春节聚会坐在一起的火爆小游戏“跳一跳",都 ...

  8. 009--EXPLAIN用法和结果分析

    在日常工作中,我们会有时会开慢查询去记录一些执行时间比较久的SQL语句,找出这些SQL语句并不意味着完事了,些时我们常常用到explain这个命令来查看一个这些SQL语句的执行计划,查看该SQL语句有 ...

  9. resize2fs命令详解

    基础命令学习目录首页 原文链接:http://blog.51cto.com/woyaoxuelinux/1870299   resize2fs:调整ext文件系统的空间大小  搭配逻辑卷lv使用方法: ...

  10. max number of clients reached Redis测试环境报错

    现象:测试服务是去redis循环取数据,早上发现服务挂了,手动登陆redis 无法输入命令,报错:max number of clients reached Redis