快速创建Spring Boot web项目集成mybatis、tk.mybatis、mybatis-generator、spring mvc、thymeleaf

陌路散爱 提交于 2020-01-03 21:25:25

创建基础SpringBoot项目集成 mybatis、tk.mybatis、mybatis-generator

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.zhun</groupId>
    <artifactId>zhun-mybatis-generator-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>zhun-mybatis-generator-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-boot-alibaba-druid.version>1.1.16</spring-boot-alibaba-druid.version>
        <mapper-spring-boot-starter.version>2.0.2</mapper-spring-boot-starter.version>
        <pagehelper-spring-boot-starter.version>1.2.5</pagehelper-spring-boot-starter.version>
    </properties>

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

        <!-- 数据库连接 Start -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${spring-boot-alibaba-druid.version}</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>${mapper-spring-boot-starter.version}</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>${pagehelper-spring-boot-starter.version}</version>
        </dependency>
        <!-- 数据库连接 End -->

        <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>3.4.4</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

创建 tk.mybatis 基础接口

  • tk.mybatis.mapper.MyMapper
package tk.mybatis.mapper;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {

}

创建mybatis-generator配置文件generatorConfig.xml

  • 所在目录${basedir}/src/main/resources/generator/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>
    <!--引入数据库连接配置-->
    <properties resource="generator/jdbc.properties"/>

    <context id="Mysql" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.MyMapper"/>
        </plugin>

        <!-- jdbc连接 -->
        <jdbcConnection
                driverClass="${jdbc.driverClass}"
                connectionURL="${jdbc.connectionURL}"
                userId="${jdbc.username}"
                password="${jdbc.password}"/>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.zhun.system.po"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaModelGenerator>

        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="mapper.system"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- targetPackage:mapper接口生成的位置
            XMLMAPPER、MIXEDMAPPER、ANNOTATEDMAPPER、MAPPER
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.zhun.system.mapper"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--
            指定数据库表
         -->
        <table tableName="sys_user"
               domainObjectName="UserPO"
               mapperName="UserMapper"
               enableSelectByExample="false" enableDeleteByExample="false"
            enableCountByExample="false" enableUpdateByExample="false">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

创建jdbc.properties

  • 所在目录${basedir}/src/main/resources/generator/jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/mybatis-generator?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=123456

创建数据库mybatis-generator

创建表sys_user

DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `account` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名(账号)',
  `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名(昵称)',
  `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码',
  `email` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',
  `phone_number` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '手机号',
  `head_url` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '头像',
  `sex` tinyint(1) NULL DEFAULT NULL COMMENT '性别',
  `intro` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '简介',
  `is_enable` tinyint(1) NULL DEFAULT NULL COMMENT '状态 0:禁用,1:正常',
  `create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `update_date` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 138 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES (1, 'admin', '超级管理员', '27bd386e70f280e24c2f4f2a549b82cf', 'admin@example.com', '17699999999', '138', NULL, '东城区', 1, '2017-08-15 21:40:39', '2017-08-15 21:41:00', '北京市市辖区');
INSERT INTO `sys_user` VALUES (2, 'test', '临时用户', '6cf3bb3deba2aadbd41ec9a22511084e', 'test@bootdo.com', NULL, NULL, NULL, NULL, 1, '2017-08-14 13:43:05', '2017-08-14 21:15:36', NULL);
INSERT INTO `sys_user` VALUES (36, 'ldh', '刘德华', 'bfd9394475754fbe45866eba97738c36', 'ldh@bootdo.com', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL);
INSERT INTO `sys_user` VALUES (123, 'zxy', '张学友', '35174ba93f5fe7267f1fb3c1bf903781', 'zxy@bootdo', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL);
INSERT INTO `sys_user` VALUES (124, 'wyf', '吴亦凡', 'e179e6f687bbd57b9d7efc4746c8090a', 'wyf@bootdo.com', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL);
INSERT INTO `sys_user` VALUES (130, 'lh', '鹿晗', '7924710cd673f68967cde70e188bb097', 'lh@bootdo.com', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL);
INSERT INTO `sys_user` VALUES (131, 'lhc', '令狐冲', 'd515538e17ecb570ba40344b5618f5d4', 'lhc@bootdo.com', NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL);
INSERT INTO `sys_user` VALUES (132, 'lyf', '刘亦菲', '7fdb1d9008f45950c1620ba0864e5fbd', 'lyf@bootdo.com', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL);
INSERT INTO `sys_user` VALUES (134, 'lyh', '李彦宏', 'dc26092b3244d9d432863f2738180e19', 'lyh@bootdo.com', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL);
INSERT INTO `sys_user` VALUES (135, 'wjl', '王健林', '3967697dfced162cf6a34080259b83aa', 'wjl@bootod.com', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL);
INSERT INTO `sys_user` VALUES (136, 'gdg', '郭德纲', '3bb1bda86bc02bf6478cd91e42135d2f', 'gdg@bootdo.com', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL);

SET FOREIGN_KEY_CHECKS = 1;

执行命令、生成sys_user表对应PO、mapper、mapper.xml

mvn mybatis-generator:generate

集成SpringMVC、thymeleaf

添加依赖

<!-- web相关 Start-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
        </dependency>
        <!-- web相关 End-->

application.yml配置


server:
  port: 8080

spring:
  datasource:
    druid:
      url: jdbc:mysql://127.0.0.1:3306/mybatis-generator?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: 123456
      initial-size: 1
      min-idle: 1
      max-active: 20
      test-on-borrow: true
      driver-class-name: com.mysql.jdbc.Driver
  thymeleaf:
    cache: false
    mode: LEGACYHTML5
    encoding: UTF-8
    servlet:
      content-type: text/html

入口类增加注解

package com.zhun;

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

@MapperScan(basePackages = {"com.zhun.**.mapper"})
@SpringBootApplication
public class MybatisGeneratorDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisGeneratorDemoApplication.class, args);
    }
}

增加服务接口

package com.zhun.system.service;

import com.github.pagehelper.PageInfo;
import com.zhun.system.po.UserPO;

import java.util.List;

public interface UserService {
    UserPO get(Long id);

    int insert(UserPO userPO);

    int update(UserPO userPO);

    int delete(Long id);

    List<UserPO> list(UserPO userPO);

    PageInfo<UserPO> page(int pageNum, int pageSize, UserPO userPO);
}

创建服务层实现

package com.zhun.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhun.system.mapper.UserMapper;
import com.zhun.system.po.UserPO;
import com.zhun.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserPO get(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int insert(UserPO userPO) {
        return userMapper.insert(userPO);
    }

    @Override
    public int update(UserPO userPO) {
        return userMapper.updateByPrimaryKey(userPO);
    }

    @Override
    public int delete(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<UserPO> list(UserPO userPO) {
        return userMapper.select(userPO);
    }

    @Override
    public PageInfo<UserPO> page(int pageNum, int pageSize, UserPO userPO) {
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(pageNum, pageSize);
        PageInfo<UserPO> pageInfo = new PageInfo<>(userMapper.select(userPO));
        return pageInfo;
    }
}

创建控制器

package com.zhun.system.controller;

import com.github.pagehelper.PageInfo;
import com.zhun.system.po.UserPO;
import com.zhun.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @GetMapping("list")
    public PageInfo list(@RequestParam(required = false, defaultValue = "1") Integer pageNumber,
                   @RequestParam(required = false, defaultValue = "5")  Integer pageSize,
                   @RequestParam(required = false) UserPO userPO) {
        return userService.page(pageNumber, pageSize, userPO);
    }

    @GetMapping
    public String index(ModelMap modelMap) {
        modelMap.put("page", userService.page(1, 5, new UserPO()));
        return "index";
    }
}

创建index.html

  • 目录 ${basedir}/src/main/resources/templates/index.html
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<table>
    <thead>
    <th>
        <td>序号</td>
        <td>昵称</td>
        <td>账号</td>
        <td>邮箱</td>
    </th>
    </thead>
    <tbody>
    <tr th:each="data,state: ${page.list}">
        <td th:text="${state.index+1}"></td>
        <td th:text="${data.name}"></td>
        <td th:text="${data.account}"></td>
        <td th:text="${data.email}"></td>
    </tr>
    </tbody>
</table>
</body>
</html>

启动项目

  • http://localhost:8080/
  • http://localhost:8080/list
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!