博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Boot(三)Spring Boot 和 MyBatis 整合
阅读量:7231 次
发布时间:2019-06-29

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

Spring Boot 整合 MyBatis有多种方式,本文使用的是starter的方式,还可以使用注解+bean配置的方式等。此外本文使用的是xml配置SQL而不是用注解。主要是 SQL 和业务代码应该隔离,方便和 DBA 校对 SQL,此外 XML 对较长的 SQL 比较清晰。

一.数据库准备

使用mySQL数据库,创建一张book表:

CREATE TABLE `book` (`id` INT(6) NOT NULL AUTO_INCREMENT,`name` VARCHAR(100) NULL DEFAULT NULL,`author` VARCHAR(100) NULL DEFAULT NULL,`price` DOUBLE NULL DEFAULT NULL,PRIMARY KEY (`id`))COLLATE='utf8_general_ci'ENGINE=InnoDBAUTO_INCREMENT=3;

二.代码示例

项目结构如下:

图片描述

1.pom.xml文件中添加 Spring Boot 的 mybatis starter 依赖,由于要使用 mysql 数据库,还需要增加 mysql 的依赖

mysql
mysql-connector-java
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.0

2.增加controller、service、dao、entity等类

entity实体类(使用MyBatis逆向工程生成):

package com.ddcx.springboot.demodatabase.entity;public class Book {    private Integer id;    private String name;    private String author;    private Double price;    //get、set方法省略}

dao:

package com.ddcx.springboot.demodatabase.mapper;import com.ddcx.springboot.demodatabase.entity.Book;import org.apache.ibatis.annotations.Param;import java.util.List;public interface BookMapper {    int insert(Book record);    List
selectAll(); Book getById(@Param(value = "id") Integer id);}

service:

package com.ddcx.springboot.demodatabase.service;import com.ddcx.springboot.demodatabase.entity.Book;import com.ddcx.springboot.demodatabase.mapper.BookMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;/*** Created by liaosi on 2017/9/26.*/@Servicepublic class BookService {    @Autowired    private BookMapper bookMapper;    public List
getAllBooks() { return bookMapper.selectAll(); } public Book getById(Integer id) { return bookMapper.getById(id); }}

controller:

package com.ddcx.springboot.demodatabase.controller;import com.ddcx.springboot.demodatabase.service.BookService;import com.google.gson.Gson;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/*** Created by liaosi on 2017/9/26.*/@RestControllerpublic class DemoController {    private static Gson gson = new Gson();    @Autowired    private BookService bookService;    @RequestMapping("/getBook/{id}")    String bookInfo(@PathVariable("id") Integer id) {        return gson.toJson(bookService.getById(id));    }}

3.将 MyBatis 的SQL映射的xml文件(也即是dao的实现)添加到 resource 下的 mapper 目录

;
insert into book (id, name, author, price) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{author,jdbcType=VARCHAR}, #{price,jdbcType=DOUBLE})

为什么要将SQL映射的xml文件的文件放在 resource 下?

因为在这个示例中使用的开发工具是IDEA,IDEA不会编译src的java目录下的xml文件,具体可参考:

4.应用启动类,需要添加 @MapperScan 注解:

package com.ddcx.springboot.demodatabase;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication//mapper 接口类包扫描@MapperScan(basePackages = "com.ddcx.springboot.demodatabase.mapper")public class ConfigApplication {   public static void main(String[] args) {      SpringApplication.run(ConfigApplication.class, args);   }}

@MapperScan注解的作用类似于 MapperScannerConfigurer ,可以扫描该包下 MyBatis 的 mapper.java 接口类注册到 IOC 容器中。

如果不使用@MapperScan注解,还可以在每个 mapper 接口类上加上 @Mapper 这个注解,但是这样做比较麻烦,如果所有的mapper接口类都在一个包下,还是使用@MapperScan注解更为方便。

图片描述

5.在application.properties配置文件中,增加 SpringBoot 和 MyBatis 整合的相关配置:

#SpringBoot整合MyBatis框架#1.加载MyBatis配置文件mybatis.mapper-locations=classpath:mapper/*.xml    //扫描classpath下mapper目录下的所有.xml文件mybatis.type-aliases-package=com.ddcx.springboot.demodatabase.entity    //实体类的包路径#2.数据库配置spring.datasource.url=jdbc:mysql://192.168.0.1:3306/java_testspring.datasource.username=rootspring.datasource.password=********spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.mapper-locations :用来指定sql映射的xml文件的位置。

mybatis.type-aliases-package :用来指定实体类的包路径。有了这个配置,在sql映射文件中,将数据库中的数据映射成某个类的对象时,不用设置该类的全类名了。例如本来在xml文件中需要这样配置的

图片描述

如果配置了mybatis.type-aliases-package=com.ddcx.springboot.demodatabase.entity,则可以写成这样:

图片描述

可以看出这个配置的作用有点类似于MyBatis配置文件中的别名处理器(typeAliases标签)中的package配置。

还有其他的一些MyBatis的配置也都可以配置到application.properties文件里,此处不再详细研究。

6.测试

启动Spring Boot应用,在postman或浏览器中访问即可。


本节示例代码已上传到github:

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

你可能感兴趣的文章
对函数式编程的理解
查看>>
Tomcat源码分析----一个http请求的经历
查看>>
Unix-Linux 编程实践教程 第二章 小结
查看>>
.未来只有坚持自己的信念.
查看>>
TODO:Golang指针使用注意事项
查看>>
五大角色和主域控制器
查看>>
QTcpserver编程
查看>>
ScrollView + Listview 实现方案优选
查看>>
redis概述与使用
查看>>
linux下如何设置和查看系统环境变量
查看>>
jaxws-webservice编程
查看>>
网众安装U盘带WINPE和MaxDOS
查看>>
Linux man文档英语单词
查看>>
oracle的权限和角色区别
查看>>
组策略管理——软件限制策略(4)
查看>>
tcp的三次握手
查看>>
u盘中的ubuntu为了减少日志系统频繁写文件所修改的/etc/fstab
查看>>
RAID浅谈
查看>>
Map接口
查看>>
IntelliJ IDEA 使用教程
查看>>