mybatis-generator自动生成代码示例

在做springboot+mybatis整合中,我们可以通过mybatis自带的mybatis-generator插件自动生成代码,这里有个前提,就是需要在数据库中先生成表,然后根据表来生成实体和dao层代码,以及mybatis的映射文件。

这里介绍如何在idea中,通过配置,一步一步实现代码生成。

1、构建maven工程,修改pom.xml,配置mybatis依赖,以及mybatis-generator插件。

2、设置mapper映射文件生成的地址:application.properties中增加配置。

3、构建数据库以及表结构。

4、设置自动生成代码配置文件。

5、构建maven任务,执行构建。

6、利用构建的结果测试。

===========================================================================

第一步: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>com.xxx.mybatis</groupId>
    <artifactId>mybatis-generate</artifactId>
    <version>1.0</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.5</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.40</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>mybatis generator</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>
    </build>
</project>

第二步:在resources目录下,新建配置文件application.properties,并设置mybatis映射文件生成的地址

server.port=9080
mybatis.mapperLocations=classpath:mapper/*.xml

第三步:准备数据库(mybatis)以及表结构

user_info

mysql> desc user_info;
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| id             | int(11)      | NO   | PRI | NULL    |       |
| name           | varchar(64)  | NO   |     | NULL    |       |
| gender         | tinyint(4)   | NO   |     | NULL    |       |
| age            | int(11)      | NO   |     | NULL    |       |
| mobile         | varchar(11)  | NO   |     | NULL    |       |
| register_mode  | varchar(10)  | NO   |     | NULL    |       |
| third_party_id | varchar(255) | NO   |     | NULL    |       |
+----------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)

 user_password

mysql> desc user_password;
+-----------------+--------------+------+-----+---------+-------+
| Field           | Type         | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+-------+
| id              | int(11)      | NO   | PRI | NULL    |       |
| encrpt_password | varchar(255) | NO   |     | NULL    |       |
| user_id         | int(11)      | NO   |     | NULL    |       |
+-----------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

 第四步:配置代码自动生成配置文件,这里需要指定连接数据库,生成实体和dao的位置,以及表与实体的映射关系。

<?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="DB2Tables" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="hadoop"
                        password="hadoop">
        </jdbcConnection>

        <javaModelGenerator targetPackage="com.xxx.mybatis.domain" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mapper"  targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xxx.mybatis.dao" 
         targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table tableName="user_info" domainObjectName="User"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
        <table tableName="user_password" domainObjectName="UserPassword"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>

    </context>
</generatorConfiguration>

table中 enableCountByExample=false,enableUpdateByExample=false,enableDeleteByExample=false,enableSelectByExample

=false,selectByExampleQueryId=false,生成的dao的方法中,可以去掉一些跟Example相关的复杂方法,一般的复杂查询,我们可以自己手动编写。

 第五步:构建:IDEA上点击Edit Configurations->新建Maven->填写工程目录working directory以及Command line:mybatis-generator:generate。接着就可以构建了。

构建以及构建之后生成的文件:

构建成功打印信息如下:

[INFO] Introspecting table user_info
[INFO] Introspecting table user_password
[INFO] Generating Record class for table user_info
[INFO] Generating Mapper Interface for table user_info
[INFO] Generating SQL Map for table user_info
[INFO] Generating Record class for table user_password
[INFO] Generating Mapper Interface for table user_password
[INFO] Generating SQL Map for table user_password
[INFO] Saving file UserMapper.xml
[INFO] Saving file UserPasswordMapper.xml
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] Saving file UserPassword.java
[INFO] Saving file UserPasswordMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.793 s
[INFO] Finished at: 2018-12-11T11:00:42+08:00
[INFO] Final Memory: 15M/305M
[INFO] ------------------------------------------------------------------------

第六步:根据生成的代码,验证mybatis与springboot整合。第二步中的配置文件application.properties做修改,增加数据库连接信息。

server.port=9080
mybatis.mapperLocations=classpath:mapper/*.xml
spring.datasource.name=mybatis
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false
spring.datasource.username=hadoop
spring.datasource.password=hadoop

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

采用数据库连接池:HikariCP,这里配置的数据库信息是给系统使用的,之前在mybatis-generator.xml中配置的数据库信息是给代码生成器使用的。

com.xxx.mybatis目录下新建App.java

package com.xxx.mybatis;

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

@SpringBootApplication
@MapperScan("com.xxx.mybatis.dao")
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

新建com.xxx.mybatis.controller包,并在其下新建UserController.java 

package com.xxx.mybatis.controller;

import com.xxx.mybatis.dao.UserMapper;
import com.xxx.mybatis.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/get")
    @ResponseBody
    public String get(){
        User user = userMapper.selectByPrimaryKey(1);
        if(user==null){
            return "user is not present.";
        }
        return user.getName();
    }
}

启动App.java类,并访问http://localhost:9080/user/get,数据库表user_info中增加一条id=1的记录,再次访问。

 至此,mybatis-generator插件自动生成代码的示例就完成了,一般的开发中,基本都是先有实体,再有表,而且复杂查询会随着业务的复杂越来越多,仅仅靠插件是无法满足的,这个示例就当学习练手了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MyBatis Generator(MyBatis-Generation)是一个用于自动生成MyBatis持久层代码的工具。通过读取数据库表的元数据信息,生成对应的Java POJO类、Mapper接口和XML映射文件,可以减少手动编写重复性的代码。 以下是MyBatis Generator的使用步骤: 1. 在Maven项目的pom.xml文件中添加MyBatis Generator插件: ```xml <build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.4.0</version> <configuration> <configurationFile>src/main/resources/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build> ``` 2. 编写generatorConfig.xml文件,指定要生成的表和对应的Java类、Mapper接口和XML映射文件的配置信息。可以参考MyBatis Generator的官方文档和示例来编写配置文件。 3. 在IDEA中打开Maven Projects面板,找到mybatis-generator-maven-plugin插件,执行mybatis-generator:generate命令。也可以在命令行中使用mvn mybatis-generator:generate命令来执行。 4. 自动生成的Java类、Mapper接口和XML映射文件会被保存在指定的目录中,可以直接使用。 注意事项: 1. 配置文件中需要指定数据库连接信息,包括数据库类型、连接URL、用户名和密码等。 2. 自动生成的Java类、Mapper接口和XML映射文件需要手动将其添加到项目中,并且需要根据实际情况进行修改和完善。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值