一、mybatis-generator的基本配置与使用

  使用mybatis-generator来生成常用的dao层类与xml,可以满足基础的增删改查功能

  1. 添加pom依赖,常用的几个依赖包

<dependency>
  <groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>

  

  2. 在resource下添加配置文件

generator.properties  数据库连接信息

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://192.168.90.221:33010/mall
jdbc.userId=root
jdbc.password=123456

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>
<properties resource="generator.properties"/>
<context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 为模型生成序列化方法-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!-- 为生成的Java模型创建一个toString方法 -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!--覆盖生成XML文件-->
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
<commentGenerator type="com.macro.mall.CommentGenerator">
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
<property name="addRemarkComments" value="true"/>
</commentGenerator> <jdbcConnection driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.userId}"
password="${jdbc.password}">
</jdbcConnection> <javaModelGenerator targetPackage="com.macro.mall.alm.model" targetProject="mall-mbg\src\main\java"/> <sqlMapGenerator targetPackage="com.macro.mall.alm.mapper" targetProject="mall-mbg\src\main\resources"/> <javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.alm.mapper"
targetProject="mall-mbg\src\main\java"/>
<!--生成全部表tableName设为%-->
<table tableName="alm_goods_sift">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>

  

  3. 配置java运行类,用于生成dao层

CommentGenerator.java :生成类中注释相关的配置

package com.macro.mall;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility; import java.util.Properties; /**
* 自定义注释生成器
* https://gitee.com/zscat-platform/mall on 2018/4/26.
*/
public class CommentGenerator extends DefaultCommentGenerator {
private boolean addRemarkComments = false; /**
* 设置用户配置的参数
*/
@Override
public void addConfigurationProperties(Properties properties) {
super.addConfigurationProperties(properties);
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
} /**
* 给字段添加注释
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
//根据参数和备注信息判断是否添加备注信息
if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
//文档注释开始
field.addJavaDocLine("/**");
//获取数据库字段的备注信息
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
for (String remarkLine : remarkLines) {
field.addJavaDocLine(" * " + remarkLine);
}
addJavadocTag(field, false);
field.addJavaDocLine(" */");
}
}
}

 Generator.java :执行器,运行该类来进行代码的生成

package com.macro.mall;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback; import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; public class Generator {
public static void main(String[] args) throws Exception {
//MBG 执行过程中的警告信息
List<String> warnings = new ArrayList<String>();
//当生成的代码重复时,覆盖原代码
boolean overwrite = true;
//读取我们的 MBG 配置文件
InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close(); DefaultShellCallback callback = new DefaultShellCallback(overwrite);
//创建 MBG
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
//执行生成代码
myBatisGenerator.generate(null);
//输出警告信息
for (String warning : warnings) {
System.out.println(warning);
}
}
}

  4. 执行Generator类用于生成具体的dao层中相关的文件,常用4个文件,model类,xml文件,Dao接口,Example类

示例中的代码将生成以下几个文件:具体内容我就不展示了。小伙伴们自己拿个数据表试一下就知道了

AlmGoodsSift.java :自动将数据库中下划线分隔的表名转换为驼峰命名的java实体类

AlmGoodsSiftExample.java :封装了一下增删改查优化的方法

AlmGoodsSiftMapper.java : 接口类

AlmGoodsSiftMapper.xml : sql语句

5. 常用的方法

5.1 查询举例使用 example条件分页查询 , 单表查询使用Example配置条件基本都可以满足了

public List<AlmGoodsSift> pageSift(PageParam pageParam) {
//使用PageHelper来传递分页参数
PageHelper.startPage(pageParam.getPageNum(),pageParam.getPageSize(),true);
AlmGoodsSiftExample goodsSiftExample = new AlmGoodsSiftExample();
AlmGoodsSiftExample.Criteria goodsSiftExampleCriteria = goodsSiftExample.createCriteria();
// 查询status与deleteStatus指定值
goodsSiftExampleCriteria.andStatusEqualTo(GoodsSiftStatusEnum.NORMAL.getCode());
goodsSiftExampleCriteria.andDeleteStatusEqualTo(DeleteStatusEnum.Normal.getValue());
// 可配置排序条件
goodsSiftExample.setOrderByClause("sort_time desc");
return goodsSiftMapper.selectByExample(goodsSiftExample);
}

  5.2 插入就不在多述了,调用insert方法即可,条件更新与删除

// 使用主键来更新,只更新参数中不为null的值
public void updateGoods(Long id) {
AlmGoodsSift status2Delete = new AlmGoodsSift();
status2Delete.setId(id);
status2Delete.setDeleteStatus(DeleteStatusEnum.Delete.getValue());
goodsSiftMapper.updateByPrimaryKeySelective(status2Delete);
} // 使用example来更新,example配置查询条件,实体类中指定要更新的字段值
public void updateGoods(Long id) {
AlmGoodsSift status2Delete = new AlmGoodsSift();
status2Delete.setDeleteStatus(DeleteStatusEnum.Delete.getValue()); AlmGoodsSiftExample goodsSiftExample = new AlmGoodsSiftExample();
AlmGoodsSiftExample.Criteria goodsSiftExampleCriteria = goodsSiftExample.createCriteria();
goodsSiftExampleCriteria.andIdEqualTo(id); goodsSiftMapper.updateByExampleSelective(status2Delete,goodsSiftExample);
} // 删除的话调用以下方法即可
goodsSiftMapper.deleteByExample(goodsSiftExample);
goodsSiftMapper.deleteByPrimaryKey(id);

  

  5.3 注意方法名updateByExampleSelective中包含selective单词,意思是传递参数中有值的话就更新,为null不做任何处理,对于有些同学要将字段值置为null值的操作,selective就满足不了你了,使用不带 selective 的方法注意了,将全字段更新


二、使用自定义Dao来更新数据:使用mybatis生成工具只能满足简单的操作,复杂的sql语句还是得自己写

  1. 配置自定义dao接口,基于生成的mapper,可以省去很多重复的配置性代码

    1.1  新建DTO用来代替实体类,有时候实体类的属性满足不了业务,查询联表时,还会返回关联对象的数据,或者自定义属性数据。(示例中包含了对象与列表对象)     

package com.macro.mall.alm.dto;
import com.macro.mall.alm.model.AlmGoodsSift;
import com.macro.mall.pms.model.PmsProduct;
import com.macro.mall.sms.model.SmsCoupon;
import lombok.Data;
import java.util.List; @Data
public class GoodsSiftDTO extends AlmGoodsSift {
/** * 名称 */
private String goodsName;
/** * 图片 */
private String goodsPic;
/** * 商品信息 */
private PmsProduct product;
/** * 优惠券列表 */
private List<SmsCoupon> coupons;
} 

    1.2  新建接口 AlmGoodsSiftDao.java文件

package com.macro.mall.alm.mapper;

import com.macro.mall.alm.dto.GoodsSiftDTO;
import java.util.List; public interface AlmGoodsSiftDao {
  // 自定义参数,自定义返回对象
List<GoodsSiftDTO> listGoodsSiftDTO(GoodsSiftDTO goodsSiftDTO);
}

    1.3  新建xml配置文件,AlmGoodsSiftDao.xml ,编写 listGoodsSiftDTO方法的sql语句,用到了 association、collection,联表查询不外乎这几种情况,使用以上配置基本上都可以满足业务需求了

<?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.macro.mall.alm.mapper.AlmGoodsSiftDao">
  <!-- resultMap继承AlmGoodsSiftMapper的BaseResultMap配置 -->
<resultMap id="GoodsSiftResultMap" type="com.macro.mall.alm.dto.GoodsSiftDTO" extends="com.macro.mall.alm.mapper.AlmGoodsSiftMapper.BaseResultMap">
<!--dto中自定义的属性映射-->
<result column="goods_name" jdbcType="VARCHAR" property="goodsName" />
<result column="goods_pic" jdbcType="VARCHAR" property="goodsPic" />
<!--关联对象-->
<association property="product" resultMap="com.macro.mall.pms.mapper.PmsProductMapper.BaseResultMap" columnPrefix="p_" />
<!--关联集合-->
<collection property="coupons" columnPrefix="c_" resultMap="com.macro.mall.sms.mapper.SmsCouponMapper.BaseResultMap"></collection>
</resultMap> <select id="listGoodsSiftDTO" parameterType="com.macro.mall.alm.dto.GoodsSiftDTO" resultMap="GoodsSiftResultMap">
select
-- 返回goods_name、goods_pic的值,字段名称与配置中column名称匹配上即可
ags.name goods_name , ags.pic goods_pic
-- 返回alm_goods_sift的所有字段信息,resultMap继承了AlmGoodsSiftMapper的配置,所以这里无需重复定义映射关系
ags.* ,
-- product表的字段都用p_开头重命名,会使用resultMap中相应的配置进行转换
pp.name p_name , pp.price p_price , pp.sale p_sale ,pp.status p_status , pp.stock p_stock ,pp.note p.note, pp.freight p_freight ,
-- coupon表的字段都用c_开头重命名
sc.note c_note, sc.code s_code , sc.amount s_amount sc.start_time s_start_time ,sc.end_time s_end_time
from alm_goods_sift ags
-- 与product表的关系是一对一,使用association来配置,将结果映射为dto中的一个对象属性
left join pms_product pp on pp.id = ags.productId
-- 与coupon表的关系是一对多,使用collection来配置,结果将封装成集合
left join sms_coupon sc on sc.coupon_id = ags.coupon_id
</select>
</mapper>

    1.4 dao接口多参数传递,普通参数+集合参数

// 查询集合范围内的数据
void listInIds(@Param("goodsId") Long goodsId, @Param("ids") List<Long> ids);

 对应xml的sql配置

    <select id="listInIds">
select * from alm_goods_sift ags where ags.good_id=#{goodsId} and ags.id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>

ok,以上就是小弟在日常工作环境中比较常用的例子了,基本上能够满足日常开发需求了~~~~~~

mybatis generator 的日常使用的更多相关文章

  1. 取代 Mybatis Generator,这款代码生成神器配置更简单,开发效率更高!

    作为一名 Java 后端开发,日常工作中免不了要生成数据库表对应的持久化对象 PO,操作数据库的接口 DAO,以及 CRUD 的 XML,也就是 mapper. Mybatis Generator 是 ...

  2. mybatis Generator生成代码及使用方式

    本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5889312.html 为什么要有mybatis mybatis 是一个 Java 的 ORM 框架,OR ...

  3. 使用MyBatis Generator自动创建代码(dao,mapping,poji)

    连接的数据库为SQL server2008,所以需要的文件为sqljdbc4.jar 使用的lib库有: 在lib库目录下新建一个src文件夹用来存放生成的文件,然后新建generatorConfig ...

  4. mybatis generator 自动生成dao层映射代码

    资源: doc url :http://www.mybatis.org/generator/ download:https://github.com/mybatis/generator/release ...

  5. mybatis generator maven插件自动生成代码

    如果你正为无聊Dao代码的编写感到苦恼,如果你正为怕一个单词拼错导致Dao操作失败而感到苦恼,那么就可以考虑一些Mybatis generator这个差价,它会帮我们自动生成代码,类似于Hiberna ...

  6. mybatis generator.xml 配置 自动生成model,dao,mapping

    generator.xml文件: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE gener ...

  7. Mybatis generator的使用

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration ...

  8. MyBatis Generator作为maven插件自动生成增删改查代码及配置文件例子

    什么是MyBatis Generator MyBatis Generator (MBG) 是一个Mybatis的代码生成器,可以自动生成一些简单的CRUD(插入,查询,更新,删除)操作代码,model ...

  9. 记一次 IDEA mybatis.generator 自定义扩展插件

    在使用 idea mybatis.generator 生成的代码,遇到 生成的代码很多重复的地方, 虽然代码是生成的,我们也不应该允许重复的代码出现,因为这些代码后期都要来手动维护. 对于生成时间戳注 ...

随机推荐

  1. ABP (.Net Core 3.1版本) 使用MySQL数据库迁移启动模板项目(1)

    最近要搭建新项目,因为还没有用过.net core,所以想用.net core的环境搭建新项目,因为不熟悉.net core的架构,所以就下载了abp项目先了解一下. 因为自己太菜了,下载了模板项目, ...

  2. oracle自定义split分割函数

    函数如下: create or replace FUNCTION fn_rme_split(p_str IN VARCHAR2, p_delimiter IN VARCHAR2) RETURN rme ...

  3. 删库吧,Bug浪——我们在同一家摸鱼的公司

    那些口口声声, Bug越来越难写人的,应该盯着你们: 像我一样,我盯着你们,满眼恨意. IT积攒了几十年的漏洞, 所有的死机.溢出.404和超时, 像是专门为你们准备的礼物. 圈复杂度.魔鬼变量.内存 ...

  4. QT5 解析JSON文件

    QT读JSON文件步骤,这里把过程记录一下,网上大多都是怎么写json的,对于读的,记录的不多 首先JSON文件格式必须为UTF-8(非UTF-8 with BOM),UTF-8 with BOM 即 ...

  5. 【SpringBoot MQ 系列】RabbitListener 消费基本使用姿势介绍

    [MQ 系列]RabbitListener 消费基本使用姿势介绍 之前介绍了 rabbitmq 的消息发送姿势,既然有发送,当然就得有消费者,在 SpringBoot 环境下,消费可以说比较简单了,借 ...

  6. 廖雪峰Python教学课后作业---datetime

    # -*- coding: utf-8 -*- import re from datetime import datetime, timezone, timedelta def to_timestam ...

  7. 微信h5页面下拉露出网页来源的解决办法

    微信h5页面下拉露出网页来源的解决办法:将document的touchmove事件禁止掉 //禁止页面拖动 document.addEventListener('touchmove', functio ...

  8. 如何嵌套一个网页html到另一个html中

    在常规网页开发中(单页应用除外哈),经常会遇到把一些通用内容的页面集中到一个页面中,需要使用这些页面只需要包含引入即可,这样有利于维护和修改,当通用页面修改时只需更改一个文件就可以了,不需要每个文件单 ...

  9. HDU 4352 XHXJ's LIS HDU(数位DP)

    HDU 4352 XHXJ's LIS HDU 题目大意 给你L到R区间,和一个数字K,然后让你求L到R区间之内满足最长上升子序列长度为K的数字有多少个 solution 简洁明了的题意总是让人无从下 ...

  10. MySQL 对window函数执行sum函数疑似Bug

    MySQL 对window函数执行sum函数疑似Bug 使用MySql的窗口函数统计数据时,发现一个小的问题,与大家一起探讨下. 环境配置: mysql-installer-community-8.0 ...