Spring Cloud

从零开始搭建Spring Cloud项目(三)集成MyBatis

2020-01-14  本文已影响0人  李白_liby

开发工具:IntelliJ IDEA 2019.2.4(Ultimate Edition)
mybatis官网:http://mybatis.org/mybatis-3/zh/index.html
mybatis generator官网:http://mybatis.org/generator/index.html

集成MyBatis

1.创建oa_user_center数据库

CREATE SCHEMA `oa_user_center` DEFAULT CHARACTER SET utf8 ;

2.创建一个用户表,并写入一条测试数据

-- ----------------------------
--  Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL COMMENT '主键',
  `name` varchar(64) NOT NULL COMMENT '姓名',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `user`
-- ----------------------------
BEGIN;
INSERT INTO `user` VALUES (2, '杜甫', '1990-01-14', '山西省太原市小店区');
COMMIT;

3.修改oa-user-center模块的pom.xml文件,使用MyBatis Generator生成工具

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.libaiii</groupId>
        <artifactId>oa-center</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>oa-user-center</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>user-center</name>
    <description>User Center</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
        <!-- Java接口和实体类 -->
        <targetJavaProject>${basedir}/src/main/java</targetJavaProject>
        <targetMapperPackage>cn.libaiii.user.center.mapper</targetMapperPackage>
        <targetModelPackage>cn.libaiii.user.center.entity</targetModelPackage>
        <!-- XML生成路径 -->
        <targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
        <targetXMLPackage>mapper</targetXMLPackage>
    </properties>

    <dependencies>
        <!-- spring mvc -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

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

        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <!-- 通用mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>4.1.5</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- 生成通用mapper的代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/builder/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.18</version>
                        <scope>runtime</scope>
                    </dependency>

                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>4.1.5</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

4.在oa-user-center/src/main/resources/builder目录下,新建generatorConfig.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`" />
        <property name="endingDelimiter" value="`" />
        <property name="mergeable" value="false" />
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.common.Mapper" />
        </plugin>

        <!-- 数据库连接 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/oa_user_center?useUnicode=true&amp;characterEncoding=UTF8&amp;nullCatalogMeansCurrent=true"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <javaModelGenerator targetPackage="${targetModelPackage}" targetProject="${targetJavaProject}"/>

        <sqlMapGenerator targetPackage="${targetXMLPackage}" targetProject="${targetResourcesProject}"/>

        <javaClientGenerator targetPackage="${targetMapperPackage}" targetProject="${targetJavaProject}" type="XMLMAPPER"/>

        <!-- 选择数据库中的表进行代码生成 -->
        <table tableName="user" domainObjectName="User">
            <!-- 主键 -->
            <generatedKey column="id" sqlStatement="MySql" identity="false" />
        </table>
    </context>
</generatorConfiguration>

5.双击mybatis-generator:generate,生成Mapper和Entity代码

生成Mapper和Entity代码

6.在oa-user-center模块中的application.yml文件内添加datasource以及mybatis配置

spring:
  application:
    name: oa-user-center
  datasource:
    url: jdbc:mysql://localhost:3306/oa_user_center?useUnicode=true&characterEncoding=UTF8&nullCatalogMeansCurrent=true
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
server:
  port: 8081

mybatis:
  mapper-locations: classpath*:mapper/*Mapper.xml
  type-aliases-package: cn.libaiii.user.center.mapper

7.在UserCenterApplication中添加@MapperScan注解

package cn.libaiii.user.center;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

/**
 * @author libai
 */
@SpringBootApplication()
@MapperScan("cn.libaiii.user.center.mapper")
public class UserCenterApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserCenterApplication.class, args);
    }
}

8.在生成的UserMapper类中,添加@Repository注解

package cn.libaiii.user.center.mapper;

import cn.libaiii.user.center.entity.User;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

/**
 * @author libai
 */
@Repository
public interface UserMapper extends Mapper<User> {
}

9.新建cn.libaiii.user.center.biz包,并创建UserBiz

package cn.libaiii.user.center.biz;


import cn.libaiii.user.center.entity.User;
import cn.libaiii.user.center.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户服务
 *
 * @author libai
 * @version 1.0
 * @date 2020/1/14
 */
@Service
public class UserBiz{

    private UserMapper userMapper;

    @Autowired
    public UserBiz(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 根据ID获取用户信息
     * @param id 用户ID
     * @return User
     */
    public User get(int id) {
        return this.userMapper.selectByPrimaryKey(id);
    }
}

10.新建cn.libaiii.user.center.rest包,并修改UserController

package cn.libaiii.user.center.rest;

import cn.libaiii.user.center.biz.UserBiz;
import cn.libaiii.user.center.entity.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户中心
 *
 * @author libai
 * @version 1.0
 * @date 2020/1/14
 */
@RestController
@RequestMapping("user")
public class UserController {

    private UserBiz userBiz;

    UserController(UserBiz userBiz) {
        this.userBiz = userBiz;
    }

    /**
     * 根据用户ID获取用户信息
     * @param id 用户ID
     * @return User
     */
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public User get(@PathVariable("id") int id) {
        return userBiz.get(id);
    }
}

11.启动服务,在浏览器中访问http://localhost:8081/user/get/1,返回如下JSON数据

{
  "id": 1,
  "name": "陶渊明",
  "birthday": "1993-10-08T05:00:00.000+0000",
  "address": "齐鲁软件园"
}

至此,MyBatis集成完成。

上一篇下一篇

猜你喜欢

热点阅读