在以前使用mybatis时,常常手写各种resultMap、sql、insert、select标签,写到炸毛,后来使用了mybatis官方提供的mybatis generator来生成mapper文件model、 dao类,但是mybatis generator坑也有很多,比如当数据库字段类型是text的时候,可能无法生成,还需要额外配置。等
最喜欢的一点还是他会生成XXXExample类,来拼接条件sql语句,但是如果没有配置对generatorConfig.xml,XXXExample类还是不会生成的。
举个generatorConfig.xml 和生成的mapper文件
具体的配置方式还是参考官网 官网
<?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:数据库的JDBC驱动的jar包地址 -->
<classPathEntry
location="E:\app\developerapps\maven\repo\mysql\mysql-connector-java\8.0.14\mysql-connector-java-8.0.14-sources.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 抑制警告 -->
<property name="suppressTypeWarnings" value="true" />
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
<!-- 是否生成注释代时间戳 -->
<property name="suppressDate" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/school" userId="root"
password="">
</jdbcConnection>
<javaModelGenerator targetPackage="com.houxinlin.school.model2"
targetProject="School\src\main\java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.mapper"
targetProject="School\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 -->
<!-- <table schema="untodo" tableName="T_USER" domainObjectName="User"/> -->
<!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
<!-- <table schema="untodo" tableName="T_USER" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"/> -->
<!--生成对应表及类名 -->
<table schema="general" tableName="tb_dynamic" domainObjectName="Dynamic">
<!--domain字段的命名规则,false:默认为驼峰命名 true:按数据库真实命名 -->
<property name="useActualColumnNames" value="false" />
<!-- 忽略列,不生成bean 字段 -->
<!-- <ignoreColumn column="FRED" /> -->
<!-- 指定列的java数据类型 -->
<!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->
</table>
</context>
</generatorConfiguration>
<?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.houxinlin.school.dao.AppConfigBeanMapper">
<resultMap id="BaseResultMap" type="com.houxinlin.school.model.AppConfigBean">
<id column="config_key" jdbcType="VARCHAR" property="configKey" />
<result column="config_value" jdbcType="VARCHAR" property="configValue" />
</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">
config_key, config_value
</sql>
<select id="selectByExample" parameterType="com.houxinlin.school.model.AppConfigBeanExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from tb_config
<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.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from tb_config
where config_key = #{configKey,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from tb_config
where config_key = #{configKey,jdbcType=VARCHAR}
</delete>
<delete id="deleteByExample" parameterType="com.houxinlin.school.model.AppConfigBeanExample">
delete from tb_config
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.houxinlin.school.model.AppConfigBean">
insert into tb_config (config_key, config_value)
values (#{configKey,jdbcType=VARCHAR}, #{configValue,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.houxinlin.school.model.AppConfigBean">
insert into tb_config
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="configKey != null">
config_key,
</if>
<if test="configValue != null">
config_value,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="configKey != null">
#{configKey,jdbcType=VARCHAR},
</if>
<if test="configValue != null">
#{configValue,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.houxinlin.school.model.AppConfigBeanExample" resultType="java.lang.Long">
select count(*) from tb_config
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update tb_config
<set>
<if test="record.configKey != null">
config_key = #{record.configKey,jdbcType=VARCHAR},
</if>
<if test="record.configValue != null">
config_value = #{record.configValue,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update tb_config
set config_key = #{record.configKey,jdbcType=VARCHAR},
config_value = #{record.configValue,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.houxinlin.school.model.AppConfigBean">
update tb_config
<set>
<if test="configValue != null">
config_value = #{configValue,jdbcType=VARCHAR},
</if>
</set>
where config_key = #{configKey,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.houxinlin.school.model.AppConfigBean">
update tb_config
set config_value = #{configValue,jdbcType=VARCHAR}
where config_key = #{configKey,jdbcType=VARCHAR}
</update>
</mapper>
后来接触了MyBatis-Plus,nb,官网 官网
这货可以生成Mapper 、 Model 、 Service 、 Controller.
首先需要集成依赖到项目中
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
编写一个普通的java类
package com.example.springdemo.demo;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GenerCode {
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("HouXinLin");
gc.setBaseColumnList(true);
gc.setBaseResultMap(true);
gc.setActiveRecord(true);
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/db_animal?allowPublicKeyRetrieval=true");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("输入模块名"));
pc.setParent("com.example.springdemo.moudl");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setEntityTableFieldAnnotationEnable(true);
// 写于父类中的公共字段
strategy.setCapitalMode(true);
strategy.setEntityColumnConstant(true);
strategy.setInclude(scanner("输入表名"));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
运行之后,输入模块名和表明之后,在src目录就会生成对应的文件
如下实例,具体各种API可以查看文档使用文档
@Controller
@RequestMapping("v1/sys")
public class TbSysController {
@Autowired
TbSysServiceImpl mTbSysService;
@GetMapping("getSysVal")
@ResponseBody
public TbSys test(@RequestParam("name")String name){
QueryWrapper<TbSys> queryWrapper= new QueryWrapper<>();
queryWrapper.eq(TbSys.SYS_NAME,name);
return mTbSysService.getOne(queryWrapper);
//||
//||
// return mTbSysService.getById(name);
}
}
如果想写自己的sql,可以通过getBaseMapper获取到Mapper
Warapper的子类有如下