【Spring-boot】整合Mybatis

摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢!

现在业界互联网流行的数据操作层框架 Mybatis,下面详解下 Springboot 如何整合 Mybatis ,这边没有使用 Mybatis Annotation 这种,是使用 xml 配置 SQL。因为我觉得 SQL 和业务代码应该隔离,方便和 DBA 校对 SQL。二者 XML 对较长的 SQL 比较清晰。

一、运行 springboot-mybatis 工程

git clone 下载工程 springboot-learning-example ,项目地址见 GitHub。下面开始运行工程步骤(Quick Start):

1.数据库准备

a.创建数据库 springbootdb:

CREATE DATABASE springbootdb;

b.创建表 city :(因为我喜欢徒步)

DROP TABLE IF EXISTS  `city`;
CREATE TABLE `city` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '城市编号',
  `province_id` int(10) unsigned  NOT NULL COMMENT '省份编号',
  `city_name` varchar(25) DEFAULT NULL COMMENT '城市名称',
  `description` varchar(25) DEFAULT NULL COMMENT '描述',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

c.插入数据

INSERT city VALUES (1 ,1,'温岭市','BYSocket 的家在温岭。');

2. 项目结构介绍

项目结构如下图所示:

org.spring.springboot.controller - Controllerorg.spring.springboot.dao - 数据操作层 DAO
org.spring.springboot.domain - 实体类
org.spring.springboot.service - 业务逻辑层
Application - 应用启动类
application.properties - 应用配置文件,应用启动会自动读取配置

3.改数据库配置

打开 application.properties 文件, 修改相应的数据源配置,比如数据源地址、账号、密码等。(如果不是用 MySQL,自行添加连接驱动 pom,然后修改驱动名配置。)

4.编译工程

在项目根目录 springboot-learning-example,运行 maven 指令:

mvn clean install

5.运行工程

右键运行 Application 应用启动类的 main 函数,然后在浏览器访问:

http://localhost:8080/api/city?cityName=温岭市

可以看到返回的 JSON 结果:

{
    "id": 1,
    "provinceId": 1,
    "cityName": "温岭市",
    "description": "我的家在温岭。"
}

如图:

二、springboot-mybatis 工程配置详解

1.pom 添加 Mybatis 依赖

<!-- Spring Boot Mybatis 依赖 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>${mybatis-spring-boot}</version>
</dependency>

整个工程的 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>springboot</groupId>
    <artifactId>springboot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mybatis :: 整合 Mybatis Demo</name>

    <!-- Spring Boot 启动父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <properties>
        <mybatis-spring-boot>1.2.0</mybatis-spring-boot>
        <mysql-connector>5.1.39</mysql-connector>
    </properties>

    <dependencies>

        <!-- Spring Boot Web 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Test 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Spring Boot Mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot}</version>
        </dependency>

        <!-- MySQL 连接驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector}</version>
        </dependency>

        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>

2.在 application.properties 应用配置文件,增加 Mybatis 相关配置

## Mybatis 配置
mybatis.typeAliasesPackage=org.spring.springboot.domain
mybatis.mapperLocations=classpath:mapper/*.xml

## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.typeAliasesPackage 配置为 org.spring.springboot.domain,指向实体类包路径。mybatis.mapperLocations 配置为 classpath 路径下 mapper 包下,* 代表会扫描所有 xml 文件。

mybatis 其他配置相关详解如下:

mybatis.config = mybatis 配置文件名称
mybatis.mapperLocations = mapper xml 文件地址
mybatis.typeAliasesPackage = 实体类包路径
mybatis.typeHandlersPackage = type handlers 处理器包路径
mybatis.check-config-location = 检查 mybatis 配置是否存在,一般命名为 mybatis-config.xml
mybatis.executorType = 执行模式。默认是 SIMPLE

3.在 Application 应用启动类添加注解 MapperScan
Application.java 代码如下:

/**
 * Spring Boot 应用启动类
 *
 * Created by bysocket on 16/4/26.
 */
// Spring Boot 应用的标识
@SpringBootApplication
// mapper 接口类扫描包配置
@MapperScan("org.spring.springboot.dao")
public class Application {

    public static void main(String[] args) {
        // 程序启动入口
        // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
        SpringApplication.run(Application.class,args);
    }
}

mapper 接口类扫描包配置注解 MapperScan :用这个注解可以注册 Mybatis mapper 接口类。

4.添加相应的 City domain类、CityDao mapper接口类
City.java:

/**
 * 城市实体类
 *
 * Created by bysocket on 07/02/2017.
 */
public class City {

    /**
     * 城市编号
     */
    private Long id;

    /**
     * 省份编号
     */
    private Long provinceId;

    /**
     * 城市名称
     */
    private String cityName;

    /**
     * 描述
     */
    private String description;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getProvinceId() {
        return provinceId;
    }

    public void setProvinceId(Long provinceId) {
        this.provinceId = provinceId;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

CityDao.java:

/**
 * 城市 DAO 接口类
 *
 * Created by bysocket on 07/02/2017.
 */
public interface CityDao {

    /**
     * 根据城市名称,查询城市信息
     *
     * @param cityName 城市名
     */
    City findByName(@Param("cityName") String cityName);
}

其他不明白的,可以 git clone 下载工程 springboot-learning-example ,工程代码注解很详细。 https://github.com/JeffLi1993/springboot-learning-example。

三、其他

利用 Mybatis-generator自动生成代码 http://www.cnblogs.com/yjmyzz/p/4210554.html
Mybatis 通用 Mapper3 https://github.com/abel533/Mapper
Mybatis 分页插件 PageHelper https://github.com/pagehelper/Mybatis-PageHelper


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
课程简介这是一门使用Java语言,SpringBoot框架,从0开发一个RESTful API应用,接近企业级的项目(我的云音乐),课程包含了基础内容,高级内容,项目封装,项目重构等知识,99%代码为手写;因为这是项目课程;所以不会深入到源码讲解某个知识点,以及原理,但会粗略的讲解下基础原理;主要是讲解如何使用系统功能,流行的第三方框架,第三方服务,完成接近企业级项目,目的是让大家,学到真正的企业级项目开发技术。适用人群刚刚毕业的学生想提高职场竞争力想学从零开发SpringBoot项目想提升SpringBoot项目开发技术想学习SpringBoot项目架构技术想学习企业级项目开发技术就是想学习SpringBoot开发能学到什么从0开发一个类似企业级项目学会能做出市面上90%通用API快速增加1到2年实际开发经验刚毕业学完后能找到满意的工作已经工作学完后最高涨薪30%课程信息全课程目前是82章,155小时,每节视频都经过精心剪辑。在线学习分辨率最高1080P课程知识点1~11章:学习方法,项目架构,编码规范,Postman使用方法,Git和Github版本控制12~16章:搭建开发环境,快速入门SpringBoot框架17~20章:快速入门MySQL数据库21~30章:MyBatis,登录注册,找回密码,发送短信,发送邮件,企业级接口配置31~41章:实现歌单,歌单标签,音乐,列表分页,视频,评论,好友功能42~48章:阿里云OSS,话题,MyBatis-plus,应用监控49~53章:Redis使用,集成Redis,SpringCache,HTTP缓存54~58章:Elasticsearch使用,集成Elasticsearch,使用ES搜索59~61章:商城,集成支付宝SDK,支付宝支付62~64章:常用哈希和加密算法,接口加密和签名65~67章:实时挤掉用户,企业级项目测试环境,企业级接口文档68~69章:SpringBoot全站HTTPS,自签证书,申请免费证书70~73章:云MySQL数据库,云Redis数据库使用,轻量级应用部署环境,域名解析74~80章:Docker使用,生产级Kubernetes集群,域名解析,集群全站HTTPS81~82章:增强和重构项目,课程总结,后续学习计划
### 回答1: Spring Boot是一个流行的Java开发框架,而MyBatis是一个Java持久化框架。Spring Boot可以与MyBatis很好地整合,使开发人员能够更轻松地创建Web应用程序和RESTful服务。 要在Spring Boot应用程序中使用MyBatis,首先需要将MyBatisMyBatis Spring Boot Starter添加到项目的依赖中。然后,在应用程序的配置文件中,需要配置数据源和MyBatis的会话工厂。接下来,创建Mapper接口和对应的Mapper XML文件,以定义数据库操作。最后,在需要使用数据库操作的地方,可以通过@Autowired注解来注入Mapper接口并调用其中定义的方法。 这些步骤的详细说明可以在Spring Boot和MyBatis的官方文档中找到。 ### 回答2: Spring Boot是一款轻量级的应用程序框架,可以帮助程序员更加方便快捷地构建基于Spring框架的Web应用程序,而MyBatis则是一个基于Java的持久层框架,能够帮助开发者更加轻松地操作数据库。在实际开发中,Spring Boot和MyBatis经常会被开发者共同使用,因此将两者进行整合是非常有必要的。 实现Spring Boot和MyBatis整合,可以分为以下几个步骤: 1. 引入MyBatis的依赖包:可以在pom.xml文件中添加MyBatis的相关依赖,例如: <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> 2. 编写MyBatis的配置文件:在resources文件夹下创建mybatis-config.xml文件,该文件中可以配置MyBatis的一些参数,例如数据库连接信息、映射文件位置等等。 3. 创建Mapper接口:可以在程序中创建Mapper接口,该接口用于定义数据库操作方法,例如查询、插入、更新等等。可以通过@Mapper注解将该接口注册为Spring Bean。 4. 创建Mapper映射文件:可以在resources文件夹下创建Mapper映射文件,该文件用于定义SQL语句以及与Mapper接口中的方法的映射关系。可以使用MyBatis的动态SQL语法来实现更加灵活的查询条件。 5. 配置MapperScannerConfigurer:可以在Spring Boot的配置类中添加MapperScannerConfigurer组件,该组件用于扫描Mapper接口所在的包路径,并将其注册为Spring Bean。 以上就是整合Spring Boot和MyBatis的基本步骤,通过这种方式可以使得开发者更加方便地操作数据库,提高开发效率,也能更加方便地进行单元测试和集成测试。同时,这种方式也为程序的扩展和维护提供了很好的支持。 ### 回答3: Spring Boot是一个快速搭建Web应用的框架,而MyBatis是一个优秀的DAO层框架。将两者结合起来,可以快速地构建出一个高效的Web应用程序。 整合Spring Boot和MyBatis时,需要引入相应的依赖包。Spring Boot中,可以使用Spring Boot MyBatis Starter来简化配置,它会自动配置好MyBatisSpring JDBC,并帮你创建DataSource和SqlSessionFactory。在pom.xml中添加如下依赖: ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> ``` 引入该starter后,就可以在你的代码中使用MyBatis了。将MyBatis的Mapper配置文件放在classpath:mybatis/mapper路径下,然后使用@Mapper注解将Mapper接口标记为MyBatis的Mapper: ```java @Mapper public interface UserMapper { User findById(Long id); } ``` 在你的代码中,你可以使用@Autowired注解将UserMapper注入到其他类中: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User findById(Long id) { return userMapper.findById(id); } } ``` 这样就可以在业务代码中愉快地使用MyBatis了。 在MyBatis中,可以使用注解方式或xml配置方式来实现SQL映射。如果使用注解方式,需要在pom.xml中引入mybatismybatis-spring-boot-starter之外的其他依赖包。使用xml配置方式则无需引入其他依赖包。 如果需要分页查询,在pom.xml中添加pagehelper的依赖: ```xml <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.10</version> </dependency> ``` 使用PageHelper.startPage()方法来开始分页查询: ```java PageHelper.startPage(pageNum, pageSize); List<User> userList = userMapper.findAll(); PageInfo<User> pageInfo = new PageInfo<>(userList); return pageInfo; ``` 总之,集成Spring Boot和MyBatis可以快速地构建高效的Web应用程序。而MyBatis的注解和XML配置使得SQL映射更加灵活和可维护。如果加上PageHelper的帮助,分页查询也很容易实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值