SpringBoot快速整合Mybatis以及mybatis-generator的使用

1. pom.xml添加mybatis等依赖

1.1 添加依赖以及mybatis-generator所需插件

外部项目dependencies分别引入springboot、mybatis、MySQL驱动、druid连接池等依赖。

pom.xml文件的插件管理器plugins标签下新增mybatis-generator-maven-plugin插件,该插件依赖mybatis-generator-core和mysql-connector-java两个jar包。

<?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>com.seckill</groupId>
    <artifactId>seckill</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>seckill</name>
    <url>http://www.awecoder.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <dependencies>
        <!--引入springboot依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--引入MySQL驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!--druid数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.19</version>
        </dependency>
        <!--springboot mybatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <!-- mybatis-generator所需依赖-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
        </dependency>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <!--锁定插件版本,避免使用maven默认版本-->
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <!--mybatis-generator插件-->
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.7</version>
                    <!--mybatis-generator插件依赖-->
                    <dependencies>
                        <dependency>
                            <groupId>org.mybatis.generator</groupId>
                            <artifactId>mybatis-generator-core</artifactId>
                            <version>1.3.6</version>
                        </dependency>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>8.0.16</version>
                        </dependency>
                    </dependencies>
                    <executions>
                        <execution>
                            <id>Generate MyBatis Artifacts</id><!--id随意取-->
                            <phase>package</phase>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                    <!--针对于重复生成文件的配置-->
                    <configuration>
                        <!-- 允许移动生成的文件 -->
                        <verbose>true</verbose>
                        <!-- 允许自动覆盖文件,生产上不允许用,会覆盖代码-->
                        <overwrite>true</overwrite>
                        <configurationFile>
                            src/main/resources/mybatis-generator.xml
                        </configurationFile>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>
</project>

由于plugin下的dependencies,Maven是无法自动识别的。因此在外面project下的dependencies中添加了mybatis-generator-core依赖,在jar包拉取到本地之后,可以删除掉外部的mybatis-generator-core依赖。教程中为了不引起误解,选择了保留。

针对于mybatis-generator的详细标签含义等请参见笔者另一篇博客。

2. 创建数据库与设计表

分别在seckill数据库下创建用户表和用户密码表。
seckill_user

CREATE TABLE `seckill_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `name` varchar(64) NOT NULL DEFAULT '' COMMENT '用户姓名',
  `gender` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1代表男性,2代表女性',
  `age` tinyint(4) NOT NULL DEFAULT '0' COMMENT '用户年龄',
  `telephone` varchar(11) NOT NULL DEFAULT '' COMMENT '用户手机号',
  `register_mode` varchar(255) NOT NULL DEFAULT '' COMMENT '用户注册方式--byphone,bywechat,byalipay',
  `third_party_id` varchar(64) NOT NULL DEFAULT '' COMMENT '第三方id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='秒杀用户表'

seckill_password

CREATE TABLE `seckill_password` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户密码id',
  `encrpt_password` varchar(128) NOT NULL DEFAULT '' COMMENT '加密密码',
  `user_id` int(11) NOT NULL DEFAULT '0' COMMENT '用户id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户密码表'

3. 通过mybatis-generator快捷创建文件

3.1 配置mybatis-generator.xml文件

文件配置在src/main/java/resources目录下,分别配置本地MySQL驱动位置、数据库连接信息、DTO、DAO、XML映射文件位置,并指定数据库表与DTO类名的映射。

<?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>
    <classPathEntry location="/home/ac/.m2/repository/mysql/mysql-connector-java/8.0.16/mysql-connector-java-8.0.16.jar"/>

    <context id="MySQLTables" targetRuntime="MyBatis3">
        <!--MySQL数据库驱动、URL、账号、密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!--声明DataObject类存放位置-->
        <javaModelGenerator targetPackage="com.seckill.dataobject" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件的存放位置-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.seckill.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--生成表与类名映射-->
        <table tableName="seckill_user" domainObjectName="UserDO" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="seckill_password" domainObjectName="UserPasswordDO" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

3.2 通过Maven运行mybatis-generator

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
执行后,mybatis会自动生成如下文件,删除UserDOExample和UserPasswordDOExample两个java文件。

[INFO] Saving file UserDOMapper.xml
[INFO] Saving file UserPasswordDOMapper.xml
[INFO] Saving file UserDOExample.java
[INFO] Saving file UserDO.java
[INFO] Saving file UserDOMapper.java
[INFO] Saving file UserPasswordDOExample.java
[INFO] Saving file UserPasswordDO.java
[INFO] Saving file UserPasswordDOMapper.java

4. 配置application.properties文件和APP启动类

4.1 application.properties

server.port=8080
## mybatis配置
mybatis.mapper-locations=classpath:mapping/*.xml

spring.datasource.name=seckill
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/seckill
spring.datasource.username=root
spring.datasource.password=123456

## 使用druid数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver

4.2 配置SpringBoot启动类

main()方法使用Spring Boot的SpringApplication.run()方法来启动应用程序,而不需要部署到外部实例。

@SpringBootApplication(scanBasePackages = {"com.seckill"})
@RestController
@MapperScan("com.seckill.dao")
public class App {
    @Autowired
    private UserDOMapper userDOMapper;

    @RequestMapping("/")
    public String home() {
        UserDO userDO = userDOMapper.selectByPrimaryKey(1);
        if (userDO == null) {
            return "用户对象不存在!";
        } else {
            return userDO.getName();
        }
    }

    public static void main(String[] args) {
        System.out.println("Hello World!");
        SpringApplication.run(App.class, args);
    }
}

执行main()方法,即可启动SpringBoot服务。浏览器访问127.0.0.1:8080或者localhost:8080即可看到"用户对象不存在!"的提示。

发布了17 篇原创文章 · 获赞 41 · 访问量 9988

猜你喜欢

转载自blog.csdn.net/awecoder/article/details/101165599