10、mybatis逆向工程(mybatis笔记)

一、概述

Mybatis官方提供逆向工厂,可以针对单表自动生成mybatis执行所需要的代码(如mapper.java、mapper.xml、pojo)。这里有很多方法可选:

1

这里我们建议使用第四种方式或者MyEclipse插件方式,最好是前者,因为不受开发工具影响。使用前者时需要下载一个工具包mybatis-generator-core-1.3.2.jar

二、使用工具逆向生成相关代码

首先我们建立一个java工程(mybatis-generator),然后导入mybatis的相关jar包和上面提到的工具包。然后编写用于生成相关类的配置文件:
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="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释  ture:是   false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!-- 数据库连接的信息 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" 
                        connectionURL="jdbc:mysql://localhost:3305/mybatis"
                        userId="root"
                        password="walp1314">
        </jdbcConnection>
        <!-- oracle -->
        <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver" 
                        connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:mybatis"
                        userId="root"
                        password="walp1314">
        </jdbcConnection> -->
        <!-- 默认false,把JDBC DECIMAL和NUMERIC类型解析为Integer,为true时解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        
        <!-- targetProject:生成pojo类的位置 -->
        <javaModelGenerator targetPackage="cn.itcast.ssm.pojo" 
                            targetProject=".\src">
            <!-- enableSubPackages:是否让schame作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        
        <!-- targetProject:mapper映射成文件的位置 -->
        <sqlMapGenerator targetPackage="cn.itcast.ssm.mapper" 
                         targetProject=".\src">
            <!-- enableSubPackages:是否让schame作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator targetPackage="cn.itcast.ssm.mapper" 
                             type="XMLMAPPER" targetProject=".\src">
            <!-- enableSubPackages: 是否让schame作为包的后缀-->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        
        <!-- 指定数据库表 -->
        <table tableName="items"></table>
        <table tableName="orders"></table>
        <table tableName="orderdetail"></table>
        <table tableName="user"></table>
        <!-- <table schema="" tableName="sys_user"></table>
        <table schema="" tableName="sys_role"></table>
        <table schema="" tableName="sys_permission"></table>
        <table schema="" tableName="sys_user_role"></table>
        <table schema="" tableName="sys_role_permission"></table> -->
        
        <!-- 有些表的字段需要指定java类型 -->
        <!-- <table schema="" tableName="">
            <columnOverride column="" javaType=""/>
        </table> -->
    </context>
</generatorConfiguration>

编写一个工具类生成相关代码:
GeneratorSqlmap.java

package cn.itcast.ssm.util;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
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;

public class GeneratorSqlmap {
    public void generator() throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
    
    public static void main(String[] args) {
        try {
            GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

说明:这个类的是直接从官网上找到的,这里不比关心其实现原理。运行此类我们就可以发现在工程中生成了相关的类。

2

注意:一般我们都是单独建一个工程,专门用来逆向生成相关代码,然后将这些代码拷贝到项目工程中,这样比较安全,避免出现同名文件的覆盖问题。这里将代码拷贝到了工程spring-mybatis02

三、使用生成的代码

测试ItemsMapper.java中的方法:

package cn.itcast.ssm.mapper;
import cn.itcast.ssm.pojo.Items;
import cn.itcast.ssm.pojo.ItemsExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface ItemsMapper {
    int countByExample(ItemsExample example);
    int deleteByExample(ItemsExample example);
    int deleteByPrimaryKey(Integer id);
    int insert(Items record);
    int insertSelective(Items record);
    List<Items> selectByExampleWithBLOBs(ItemsExample example);
    List<Items> selectByExample(ItemsExample example);
    Items selectByPrimaryKey(Integer id);
    int updateByExampleSelective(@Param("record") Items record, @Param("example") ItemsExample example);
    int updateByExampleWithBLOBs(@Param("record") Items record, @Param("example") ItemsExample example);
    int updateByExample(@Param("record") Items record, @Param("example") ItemsExample example);
    int updateByPrimaryKeySelective(Items record);
    int updateByPrimaryKeyWithBLOBs(Items record);
    int updateByPrimaryKey(Items record);
}

测试方法ItemsMapperTest.java

package cn.itcast.ssm.mapper;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.ssm.pojo.Items;
import cn.itcast.ssm.pojo.ItemsExample;

public class ItemsMapperTest {
    private ApplicationContext applicationContext;
    private ItemsMapper itemsMapper;//这里我们使用的是spring的自动扫描后注入的
    
    @Before
    public void setUp()throws Exception{
        applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
    }
    //根据主键删除
    @Test
    public void testDeleteByPrimaryKey() {
        
    }

    @Test
    public void testInsert() {
        //构造Items对象
        Items items = new Items();
        items.setName("手机");
        items.setPrice(1999f);
        itemsMapper.insert(items);
    }
    
    //自定义条件查询
    @Test
    public void testSelectByExample() {
        ItemsExample itemsExample = new ItemsExample();
        //通过criteria构造查询条件
        ItemsExample.Criteria criteria = itemsExample.createCriteria();
        criteria.andNameEqualTo("台式机");//这就是我们添加的查询条件
        //可能返回多天记录
        List<Items> list = itemsMapper.selectByExample(itemsExample);
        for(Items tmp : list){
            System.out.println(tmp.getName());
        }
    }
    
    //根据主键查询
    @Test
    public void testSelectByPrimaryKey() {
        Items items = itemsMapper.selectByPrimaryKey(1);
        System.out.println(items.getName());
    }
    
    //更新
    @Test
    public void testUpdateByPrimaryKey() {
        //对所有字段进行更新,需要先查询出来再更新
        Items items = itemsMapper.selectByPrimaryKey(1);
        items.setName("水杯");
        itemsMapper.updateByPrimaryKey(items);
        //如果传入字段不为空才更新,一般用在批量更新中,不需要先查询再更新
        //itemsMapper.updateByPrimaryKeySelective(items);
    }
}

说明:这里我们是对相关方法的一个简要测试。其他内容还需要再研究。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,398评论 0 4
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,082评论 25 707
  • 日夜穿梭何太急 寒窗共对九张机 一生织得相思句 遍看红尘无处题 一张机 春蚕吐尽万绦丝 只因情有千千结 柔肠...
    丫头317阅读 330评论 0 0
  • 准备一点一点将自己曾经阅读的书目整理为电子版本,方便以后查阅和搜索。 1 英文小说原版系列 1.1 Animal ...
    LoveLJM阅读 1,355评论 0 3
  • [PHP] - Laravel - CSRF token禁用方法方法一 打开文件:app\Http\Kernel....
    金星show阅读 529评论 0 0