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);
    }
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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