本文介绍如何将Maven和Mybatis-Generator配合使用。

简介

Mybatis-Generator是Mybatis提供的一个便捷型插件,自动可以为项目生产对应的实体类,Mapper,dao层。

官网文档:http://www.mybatis.org/generator/index.html

入门案例

本文使用SpringBoot结合Mybatis-Generator插件使用,数据库Mysql。

新建项目

新建一个SpringBoot项目。

依赖文件

在项目pom文件中,引入Mybatis-Generator插件,并且引入Mybatis和Mysql依赖。完整pom代码如下:

<?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.dalaoyang</groupId>
<artifactId>springboot_generator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>springboot_generator</name>
<description>springboot_generator</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.15.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<id>mybatis-generator</id>
<phase>deploy</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- Mybatis-Generator 工具配置文件的位置 -->
<configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
</build> </project>

配置Mybatis-Generator配置

在pom文件中配置的Mybatis-Generator 工具配置文件的位置新建一个generatorConfig.xml,(本文案例配置的位置是src/main/resources/mybatis-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>
<!--执行generator插件生成文件的命令: call mvn mybatis-generator:generate -e -->
<!-- 引入配置文件 -->
<properties resource="application.properties"/>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<!--<classPathEntry location="D:generator_mybatismysql-connector-java-5.1.24-bin.jar" /> --> <!-- 一个数据库一个context -->
<!--defaultModelType="flat" 大数据字段,不分表 -->
<context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;
一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true" />
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8" />
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" /> <!-- 格式化java代码 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代码 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" /> <plugin type="org.mybatis.generator.plugins.ToStringPlugin" /> <!-- 注释 -->
<commentGenerator >
<property name="suppressAllComments" value="false"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳-->
</commentGenerator> <!-- jdbc连接 -->
<jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}" />
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver> <!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="com.dalaoyang.entity" targetProject="${mybatis.project}" >
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="mapper" targetProject="${mybatis.resources}" >
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapxml对应client,也就是接口dao -->
<javaClientGenerator targetPackage="com.dalaoyang.dao" targetProject="${mybatis.project}" type="XMLMAPPER" >
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 -->
<table tableName="user" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
<property name="useActualColumnNames" value="false" />
<!-- 数据库表主键 -->
<generatedKey column="id" sqlStatement="Mysql" identity="true" />
</table>
<table tableName="book" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
<property name="useActualColumnNames" value="false" />
<!-- 数据库表主键 -->
<generatedKey column="id" sqlStatement="Mysql" identity="true" />
</table>
</context>
</generatorConfiguration>

配置application.properties

配置项目的application.properties,其中数据库信息,Mapper地址之前都有过介绍,具体SpringBoot-Mybatis配置可以参考:

《SpringBoot+Mybatis+MySql学习》

本文配置如下:

## mapper xml 文件地址
mybatis.mapper-locations=classpath*:mapper/*Mapper.xml ##数据库url
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##数据库用户名
spring.datasource.username=root
##数据库密码
spring.datasource.password=123456
##数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver #Mybatis Generator configuration
#dao类和实体类的位置
mybatis.project =src/main/java
#mapper文件的位置
mybatis.resources=src/main/resources

到这里其实配置就完成了,可以体验Mybatis-Generator插件的优点了,在右侧Maven处点击如图所示位置,如图:

点击完成后,可以看到Mapper,dao,实体类都已经创建好了,如图:

创建完成会给我生成几个默认的建当方法,如UserMapper代码如下:

package com.dalaoyang.dao;

import com.dalaoyang.entity.User;
import org.apache.ibatis.annotations.Mapper; import java.util.List; public interface UserMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
int deleteByPrimaryKey(Long id); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
int insert(User record); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
User selectByPrimaryKey(Long id); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
List<User> selectAll(); /**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
int updateByPrimaryKey(User record);
}

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.dalaoyang.dao.UserMapper" >
<resultMap id="BaseResultMap" type="com.dalaoyang.entity.User" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<id column="id" property="id" jdbcType="BIGINT" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="user_password" property="userPassword" jdbcType="VARCHAR" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
delete from user
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.dalaoyang.entity.User" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
SELECT LAST_INSERT_ID()
</selectKey>
insert into user (user_name, user_password)
values (#{userName,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="com.dalaoyang.entity.User" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
update user
set user_name = #{userName,jdbcType=VARCHAR},
user_password = #{userPassword,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select id, user_name, user_password
from user
where id = #{id,jdbcType=BIGINT}
</select>
<select id="selectAll" resultMap="BaseResultMap" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select id, user_name, user_password
from user
</select>
</mapper>

测试使用

新增测试方法

在UserMapper上加入注解@Mapper表明是持久化映射层,启动类上加入注解@RestController进行测试,这里简单调用一个查询所有的方法selectAll,启动类代码如下:

@SpringBootApplication
@RestController
public class SpringbootGeneratorApplication { @Autowired
private UserMapper userMapper; @GetMapping("/findAll")
public List<User> findAll(){
return userMapper.selectAll();
} public static void main(String[] args) {
SpringApplication.run(SpringbootGeneratorApplication.class, args);
}
}

运行测试

运行项目,浏览器访问localhost:8080/findAll如图所示:

源码下载 :大老杨码云

SpringBoot使用Mybatis-Generator的更多相关文章

  1. SpringBoot 添加mybatis generator 自动生成代码插件

    自动生成数据层代码,提高开发效率 1.pom添加插件,并指定配置文件路径 <!-- mybatis generator 自动生成代码插件 --> <plugin> <gr ...

  2. springboot(十三):springboot结合mybatis generator逆向工程自动生成代码

    错信息generate failed: Exception getting JDBC Driver: com.mysql.jdbc.Driver 上网查了一下,发现原来是generator这个插件在运 ...

  3. springboot整合mybatis+generator

    源码地址:springboot-integration 如果你觉得解决了你使用的需求,欢迎fork|star.

  4. springboot整合mybatis通用Mapper

    参考: https://blog.csdn.net/x18707731829/article/details/82814095 https://www.jianshu.com/p/6d2103451d ...

  5. Java逆向工程SpringBoot + Mybatis Generator + MySQL

    Java逆向工程SpringBoot+ Mybatis Generator + MySQL Meven pop.xml文件添加引用: <dependency> <groupId> ...

  6. SpringBoot入门教程(四)MyBatis generator 注解方式和xml方式

    MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 XML ...

  7. springboot整合mybatis(使用MyBatis Generator)

    引入依赖 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> ...

  8. springboot学习随笔(四):Springboot整合mybatis(含generator自动生成代码)

    这章我们将通过springboot整合mybatis来操作数据库 以下内容分为两部分,一部分主要介绍generator自动生成代码,生成model.dao层接口.dao接口对应的sql配置文件 第一部 ...

  9. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  10. springboot集成mybatis及mybatis generator工具使用

    原文链接 前言mybatis是一个半自动化的orm框架,所谓半自动化就是mybaitis只支持数据库查出的数据映射到pojo类上,而实体到数据库的映射需要自己编写sql语句实现,相较于hibernat ...

随机推荐

  1. 页面初始化的js函数要放在最最最最最最最前边!否则没效果

    简单说一下这个情况,html的页面的各部分都是动态渲染的,所以头部的某些个样式调用函数需要在页面初始化的时候被加载,这个我也是知道的,结果后边代码敲着敲着,就把这个事儿给忘了,然后启动项目的时候,页面 ...

  2. Metasploit

    1.启动Metasploit 声明:本次渗透测试的主机是我自己在自己的攻击主机上搭建的另一个操作系统,为了真实性设置了常见的IP地址,如有重合但绝对不是任何实体公司或者单位的IP地址. 所以不承担任何 ...

  3. 在线版区间众数 hzw的代码。。

    /* 查询区间众数,要求强制在线 设有T个块 1.众数只可能在大块[L,R]里或者两端[l,L) (R,r]里出现 2.大块的众数只要预处理打表一下即可,复杂度n*T(这样的区间有T*T个) 3.两端 ...

  4. PyCharm里面执行代码没问题,Jenkins执行时找不到第三方库

    在PyCharm里面代码执行没问题 本地cmd执行也没问题 Jenkins执行时报错 原因是第三方库是用PyCharm安装的,后来在Jenkins服务器上用pip装好第三方库后,就可以执行了 再执行 ...

  5. C++ friend友元函数和友元类(转)

    一个类中可以有 public.protected.private 三种属性的成员,通过对象可以访问 public 成员,只有本类中的函数可以访问本类的 private 成员.现在,我们来介绍一种例外情 ...

  6. Controller中方法返回值其他类型需要添加jackson依赖

    第一个 第二个: 第三个 https://www.cnblogs.com/codejackanapes/p/5569013.html:json的博客园 springmvc默认的是:2.Jackson: ...

  7. Stuck on "Authenticating with iTunes Store"

    https://forums.developer.apple.com/thread/76803 Try this, it fixed it for me. Open Terminal and run: ...

  8. Html 文字排版

    文字竖立排版,方法一 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="v ...

  9. 自定义Spring标签

    写了好几次了,结果一段时间之后就忘记了自己有写好的example,但是最后还是决定重新写一遍,把这个步骤记录下来 首先看整个项目结构 从transaction.xml开始,虽然图上报错了,实际上运行并 ...

  10. [转] Nodejs 进阶:Express 常用中间件 body-parser 实现解析

    写在前面 body-parser是非常常用的一个express中间件,作用是对post请求的请求体进行解析.使用非常简单,以下两行代码已经覆盖了大部分的使用场景. app.use(bodyParser ...