SpringBoot集成Mybatis自动生成代码(IDEA版本)

1.pom文件添加如下依赖
<dependencies>
	<!-- 整合mybatis -->
	<dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>2.1.2</version>
	</dependency>
	<!-- mybatis驱动 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.38</version>
	</dependency>
	<!-- dbcp数据源 -->
	<dependency>
		<groupId>commons-dbcp</groupId>
		<artifactId>commons-dbcp</artifactId>
		<version>1.4</version>
	</dependency>
	<!-- MBG -->
	<dependency>
		<groupId>org.mybatis.generator</groupId>
		<artifactId>mybatis-generator-core</artifactId>
		<version>1.3.5</version>
	</dependency>
	<!-- 通用Mapper的依赖 -->
	<dependency>
		<groupId>tk.mybatis</groupId>
		<artifactId>mapper-spring-boot-starter</artifactId>
		<version>2.1.5</version>
	</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<configuration>
				<fork>true</fork>
				<!--增加jvm参数-->
				<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
			</configuration>
		</plugin>
		<!-- MBG -->
		<plugin>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-maven-plugin</artifactId>
			<version>1.3.5</version>
		</plugin>
	</plugins>
</build>
2.resources下添加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>
    <!--数据库驱动-->
    <classPathEntry
            location="mysql-connector-java-5.1.38.jar包绝对路径"/>
    <context id="mysql" targetRuntime="MyBatis3">
        <!--是否忽略注释的生成 true -->
        <commentGenerator>
            <!-- 这个元素用来去除指定生成的注释中是否包含生成的日期 false:表示包含 -->
            <!-- 如果生成日期,会造成即使修改一个字段,整个实体类所有属性都会发生变化,不利于版本控制,所以
            设置为true -->
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:-->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接地址账号密码-->
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="connectionURL"
                        userId="userId"
                        password="password">
        </jdbcConnection>
        <!--生成Model类存放位置 entity-->
        <javaModelGenerator targetPackage="com.bot.entity" 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>
        <!--生成Dao接口存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.bot.mapper" targetProject="./src/main/java">
            <!--是否合并-->
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--生成对应表及类名-->
        <table tableName="生产的表" domainObjectName="对应的实体类"></table>
    </context>
</generatorConfiguration>
3.application.properties文件添加如下配置
server.port=9999
server.servlet.context-path=/mybatisGenerator

spring.datasource.type=org.apache.commons.dbcp.BasicDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://ip:3306/库名?characterEncoding=UTF-8&&useSSL=false
spring.datasource.username=username
spring.datasource.password=password
4.在maven的Plugins中找到mybatis-generator双击mybatis-generator:generate 即可自动生成

在这里插入图片描述

5.部分代码展示

在这里插入图片描述
User

package com.bot.entity;

import java.util.Date;

public class User {
   private Integer userId;

   private String username;

   private String password;

   private String mobile;

   private String email;

   private String roleId;

   private Integer status;

   private String authKey;

   private String rowCrtUsr;

   private Date rowCrtTs;

   private String recUpdUsr;

   private Date recUpdTs;

   public Integer getUserId() {
       return userId;
   }

   public void setUserId(Integer userId) {
       this.userId = userId;
   }

   public String getUsername() {
       return username;
   }

   public void setUsername(String username) {
       this.username = username == null ? null : username.trim();
   }

   public String getPassword() {
       return password;
   }

   public void setPassword(String password) {
       this.password = password == null ? null : password.trim();
   }

   public String getMobile() {
       return mobile;
   }

   public void setMobile(String mobile) {
       this.mobile = mobile == null ? null : mobile.trim();
   }

   public String getEmail() {
       return email;
   }

   public void setEmail(String email) {
       this.email = email == null ? null : email.trim();
   }

   public String getRoleId() {
       return roleId;
   }

   public void setRoleId(String roleId) {
       this.roleId = roleId == null ? null : roleId.trim();
   }

   public Integer getStatus() {
       return status;
   }

   public void setStatus(Integer status) {
       this.status = status;
   }

   public String getAuthKey() {
       return authKey;
   }

   public void setAuthKey(String authKey) {
       this.authKey = authKey == null ? null : authKey.trim();
   }

   public String getRowCrtUsr() {
       return rowCrtUsr;
   }

   public void setRowCrtUsr(String rowCrtUsr) {
       this.rowCrtUsr = rowCrtUsr == null ? null : rowCrtUsr.trim();
   }

   public Date getRowCrtTs() {
       return rowCrtTs;
   }

   public void setRowCrtTs(Date rowCrtTs) {
       this.rowCrtTs = rowCrtTs;
   }

   public String getRecUpdUsr() {
       return recUpdUsr;
   }

   public void setRecUpdUsr(String recUpdUsr) {
       this.recUpdUsr = recUpdUsr == null ? null : recUpdUsr.trim();
   }

   public Date getRecUpdTs() {
       return recUpdTs;
   }

   public void setRecUpdTs(Date recUpdTs) {
       this.recUpdTs = recUpdTs;
   }
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bot.mapper.UserMapper">
   <resultMap id="BaseResultMap" type="com.bot.entity.User">
       <id column="user_id" jdbcType="INTEGER" property="userId"/>
       <result column="username" jdbcType="VARCHAR" property="username"/>
       <result column="password" jdbcType="VARCHAR" property="password"/>
       <result column="mobile" jdbcType="VARCHAR" property="mobile"/>
       <result column="email" jdbcType="VARCHAR" property="email"/>
       <result column="role_id" jdbcType="VARCHAR" property="roleId"/>
       <result column="status" jdbcType="INTEGER" property="status"/>
       <result column="auth_key" jdbcType="VARCHAR" property="authKey"/>
       <result column="row_crt_usr" jdbcType="VARCHAR" property="rowCrtUsr"/>
       <result column="row_crt_ts" jdbcType="TIMESTAMP" property="rowCrtTs"/>
       <result column="rec_upd_usr" jdbcType="VARCHAR" property="recUpdUsr"/>
       <result column="rec_upd_ts" jdbcType="TIMESTAMP" property="recUpdTs"/>
   </resultMap>
   <sql id="Example_Where_Clause">
       <where>
           <foreach collection="oredCriteria" item="criteria" separator="or">
               <if test="criteria.valid">
                   <trim prefix="(" prefixOverrides="and" suffix=")">
                       <foreach collection="criteria.criteria" item="criterion">
                           <choose>
                               <when test="criterion.noValue">
                                   and ${criterion.condition}
                               </when>
                               <when test="criterion.singleValue">
                                   and ${criterion.condition} #{criterion.value}
                               </when>
                               <when test="criterion.betweenValue">
                                   and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                               </when>
                               <when test="criterion.listValue">
                                   and ${criterion.condition}
                                   <foreach close=")" collection="criterion.value" item="listItem" open="("
                                            separator=",">
                                       #{listItem}
                                   </foreach>
                               </when>
                           </choose>
                       </foreach>
                   </trim>
               </if>
           </foreach>
       </where>
   </sql>
   <sql id="Update_By_Example_Where_Clause">
       <where>
           <foreach collection="example.oredCriteria" item="criteria" separator="or">
               <if test="criteria.valid">
                   <trim prefix="(" prefixOverrides="and" suffix=")">
                       <foreach collection="criteria.criteria" item="criterion">
                           <choose>
                               <when test="criterion.noValue">
                                   and ${criterion.condition}
                               </when>
                               <when test="criterion.singleValue">
                                   and ${criterion.condition} #{criterion.value}
                               </when>
                               <when test="criterion.betweenValue">
                                   and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                               </when>
                               <when test="criterion.listValue">
                                   and ${criterion.condition}
                                   <foreach close=")" collection="criterion.value" item="listItem" open="("
                                            separator=",">
                                       #{listItem}
                                   </foreach>
                               </when>
                           </choose>
                       </foreach>
                   </trim>
               </if>
           </foreach>
       </where>
   </sql>
   <sql id="Base_Column_List">
       user_id
       , username, password, mobile, email, role_id, status, auth_key, row_crt_usr, 
   row_crt_ts, rec_upd_usr, rec_upd_ts
   </sql>
   <select id="selectByExample" parameterType="com.bot.entity.UserExample" resultMap="BaseResultMap">
       select
       <if test="distinct">
           distinct
       </if>
       <include refid="Base_Column_List"/>
       from t_user
       <if test="_parameter != null">
           <include refid="Example_Where_Clause"/>
       </if>
       <if test="orderByClause != null">
           order by ${orderByClause}
       </if>
   </select>
   <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
       select
       <include refid="Base_Column_List"/>
       from t_user
       where user_id = #{userId,jdbcType=INTEGER}
   </select>
   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
       delete
       from t_user
       where user_id = #{userId,jdbcType=INTEGER}
   </delete>
   <delete id="deleteByExample" parameterType="com.bot.entity.UserExample">
       delete from t_user
       <if test="_parameter != null">
           <include refid="Example_Where_Clause"/>
       </if>
   </delete>
   <insert id="insert" parameterType="com.bot.entity.User">
       insert into t_user (user_id, username, password,
                           mobile, email, role_id,
                           status, auth_key, row_crt_usr,
                           row_crt_ts, rec_upd_usr, rec_upd_ts)
       values (#{userId,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
               #{mobile,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{roleId,jdbcType=VARCHAR},
               #{status,jdbcType=INTEGER}, #{authKey,jdbcType=VARCHAR}, #{rowCrtUsr,jdbcType=VARCHAR},
               #{rowCrtTs,jdbcType=TIMESTAMP}, #{recUpdUsr,jdbcType=VARCHAR}, #{recUpdTs,jdbcType=TIMESTAMP})
   </insert>
   <insert id="insertSelective" parameterType="com.bot.entity.User">
       insert into t_user
       <trim prefix="(" suffix=")" suffixOverrides=",">
           <if test="userId != null">
               user_id,
           </if>
           <if test="username != null">
               username,
           </if>
           <if test="password != null">
               password,
           </if>
           <if test="mobile != null">
               mobile,
           </if>
           <if test="email != null">
               email,
           </if>
           <if test="roleId != null">
               role_id,
           </if>
           <if test="status != null">
               status,
           </if>
           <if test="authKey != null">
               auth_key,
           </if>
           <if test="rowCrtUsr != null">
               row_crt_usr,
           </if>
           <if test="rowCrtTs != null">
               row_crt_ts,
           </if>
           <if test="recUpdUsr != null">
               rec_upd_usr,
           </if>
           <if test="recUpdTs != null">
               rec_upd_ts,
           </if>
       </trim>
       <trim prefix="values (" suffix=")" suffixOverrides=",">
           <if test="userId != null">
               #{userId,jdbcType=INTEGER},
           </if>
           <if test="username != null">
               #{username,jdbcType=VARCHAR},
           </if>
           <if test="password != null">
               #{password,jdbcType=VARCHAR},
           </if>
           <if test="mobile != null">
               #{mobile,jdbcType=VARCHAR},
           </if>
           <if test="email != null">
               #{email,jdbcType=VARCHAR},
           </if>
           <if test="roleId != null">
               #{roleId,jdbcType=VARCHAR},
           </if>
           <if test="status != null">
               #{status,jdbcType=INTEGER},
           </if>
           <if test="authKey != null">
               #{authKey,jdbcType=VARCHAR},
           </if>
           <if test="rowCrtUsr != null">
               #{rowCrtUsr,jdbcType=VARCHAR},
           </if>
           <if test="rowCrtTs != null">
               #{rowCrtTs,jdbcType=TIMESTAMP},
           </if>
           <if test="recUpdUsr != null">
               #{recUpdUsr,jdbcType=VARCHAR},
           </if>
           <if test="recUpdTs != null">
               #{recUpdTs,jdbcType=TIMESTAMP},
           </if>
       </trim>
   </insert>
   <select id="countByExample" parameterType="com.bot.entity.UserExample" resultType="java.lang.Long">
       select count(*) from t_user
       <if test="_parameter != null">
           <include refid="Example_Where_Clause"/>
       </if>
   </select>
   <update id="updateByExampleSelective" parameterType="map">
       update t_user
       <set>
           <if test="record.userId != null">
               user_id = #{record.userId,jdbcType=INTEGER},
           </if>
           <if test="record.username != null">
               username = #{record.username,jdbcType=VARCHAR},
           </if>
           <if test="record.password != null">
               password = #{record.password,jdbcType=VARCHAR},
           </if>
           <if test="record.mobile != null">
               mobile = #{record.mobile,jdbcType=VARCHAR},
           </if>
           <if test="record.email != null">
               email = #{record.email,jdbcType=VARCHAR},
           </if>
           <if test="record.roleId != null">
               role_id = #{record.roleId,jdbcType=VARCHAR},
           </if>
           <if test="record.status != null">
               status = #{record.status,jdbcType=INTEGER},
           </if>
           <if test="record.authKey != null">
               auth_key = #{record.authKey,jdbcType=VARCHAR},
           </if>
           <if test="record.rowCrtUsr != null">
               row_crt_usr = #{record.rowCrtUsr,jdbcType=VARCHAR},
           </if>
           <if test="record.rowCrtTs != null">
               row_crt_ts = #{record.rowCrtTs,jdbcType=TIMESTAMP},
           </if>
           <if test="record.recUpdUsr != null">
               rec_upd_usr = #{record.recUpdUsr,jdbcType=VARCHAR},
           </if>
           <if test="record.recUpdTs != null">
               rec_upd_ts = #{record.recUpdTs,jdbcType=TIMESTAMP},
           </if>
       </set>
       <if test="_parameter != null">
           <include refid="Update_By_Example_Where_Clause"/>
       </if>
   </update>
   <update id="updateByExample" parameterType="map">
       update t_user
       set user_id = #{record.userId,jdbcType=INTEGER},
       username = #{record.username,jdbcType=VARCHAR},
       password = #{record.password,jdbcType=VARCHAR},
       mobile = #{record.mobile,jdbcType=VARCHAR},
       email = #{record.email,jdbcType=VARCHAR},
       role_id = #{record.roleId,jdbcType=VARCHAR},
       status = #{record.status,jdbcType=INTEGER},
       auth_key = #{record.authKey,jdbcType=VARCHAR},
       row_crt_usr = #{record.rowCrtUsr,jdbcType=VARCHAR},
       row_crt_ts = #{record.rowCrtTs,jdbcType=TIMESTAMP},
       rec_upd_usr = #{record.recUpdUsr,jdbcType=VARCHAR},
       rec_upd_ts = #{record.recUpdTs,jdbcType=TIMESTAMP}
       <if test="_parameter != null">
           <include refid="Update_By_Example_Where_Clause"/>
       </if>
   </update>
   <update id="updateByPrimaryKeySelective" parameterType="com.bot.entity.User">
       update t_user
       <set>
           <if test="username != null">
               username = #{username,jdbcType=VARCHAR},
           </if>
           <if test="password != null">
               password = #{password,jdbcType=VARCHAR},
           </if>
           <if test="mobile != null">
               mobile = #{mobile,jdbcType=VARCHAR},
           </if>
           <if test="email != null">
               email = #{email,jdbcType=VARCHAR},
           </if>
           <if test="roleId != null">
               role_id = #{roleId,jdbcType=VARCHAR},
           </if>
           <if test="status != null">
               status = #{status,jdbcType=INTEGER},
           </if>
           <if test="authKey != null">
               auth_key = #{authKey,jdbcType=VARCHAR},
           </if>
           <if test="rowCrtUsr != null">
               row_crt_usr = #{rowCrtUsr,jdbcType=VARCHAR},
           </if>
           <if test="rowCrtTs != null">
               row_crt_ts = #{rowCrtTs,jdbcType=TIMESTAMP},
           </if>
           <if test="recUpdUsr != null">
               rec_upd_usr = #{recUpdUsr,jdbcType=VARCHAR},
           </if>
           <if test="recUpdTs != null">
               rec_upd_ts = #{recUpdTs,jdbcType=TIMESTAMP},
           </if>
       </set>
       where user_id = #{userId,jdbcType=INTEGER}
   </update>
   <update id="updateByPrimaryKey" parameterType="com.bot.entity.User">
       update t_user
       set username    = #{username,jdbcType=VARCHAR},
           password    = #{password,jdbcType=VARCHAR},
           mobile      = #{mobile,jdbcType=VARCHAR},
           email       = #{email,jdbcType=VARCHAR},
           role_id     = #{roleId,jdbcType=VARCHAR},
           status      = #{status,jdbcType=INTEGER},
           auth_key    = #{authKey,jdbcType=VARCHAR},
           row_crt_usr = #{rowCrtUsr,jdbcType=VARCHAR},
           row_crt_ts  = #{rowCrtTs,jdbcType=TIMESTAMP},
           rec_upd_usr = #{recUpdUsr,jdbcType=VARCHAR},
           rec_upd_ts  = #{recUpdTs,jdbcType=TIMESTAMP}
       where user_id = #{userId,jdbcType=INTEGER}
   </update>
</mapper>
6.gitee地址 代码自取

mybatisGenerator

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 MyBatis Generator 插件生成代码MyBatis Generator 是一个基于 MyBatis代码生成工具,可以根据数据库表结构自动生成对应的实体类、Mapper 接口和 XML 映射文件等。 下面是集成 MyBatis Generator 插件的步骤: 1. 在 pom.xml 中添加 MyBatis Generator 插件依赖: ``` <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency> ``` 2. 在 pom.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> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> </dependencies> </plugin> </plugins> </build> ``` 其中,`configurationFile` 指定了配置文件的路径,`verbose` 表示是否输出详细日志,`overwrite` 表示是否覆盖已有的文件。 3. 在 `src/main/resources` 目录下创建 `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="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true"/> </commentGenerator> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?serverTimezone=UTC" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <javaModelGenerator targetPackage="com.example.demo.entity" 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.example.demo.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <table tableName="user" domainObjectName="User" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <property name="useActualColumnNames" value="true"/> </table> </context> </generatorConfiguration> ``` 其中,`jdbcConnection` 指定数据库连接信息,`javaModelGenerator` 指定实体类生成的包名和路径,`sqlMapGenerator` 指定 XML 映射文件生成的包名和路径,`javaClientGenerator` 指定 Mapper 接口生成的包名和路径,`table` 指定要生成代码的表名和实体类名。 4. 在 IDEA 的 Maven Projects 中双击插件 mybatis-generator-maven-plugin 的 mybatis-generator:generate,执行生成代码操作。 5. 在生成的代码中,可以根据需要进行修改和补充。 这样就完成了 Spring Boot 集成 MyBatis Generator 插件生成代码的过程。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值