zoukankan      html  css  js  c++  java
  • mybatis逆向工程

    前言

    mybatis逆向工程可以很方便的帮我们创建好常用的单表操作,对于更加复杂的业务流程,请自己添加相应的接口即可。

    源码-待补充

    引用并生成

    引用

    <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.5</version>
    </dependency>
    

    配置文件

    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">
    
            <!-- JavaBean 实现 序列化 接口 -->
            <plugin type="org.mybatis.generator.plugins.SerializablePlugin">
            </plugin>
            <!-- genenat entity时,生成toString -->
            <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
            <!-- 自定义查询指定字段  -->
            <plugin type="org.mybatis.generator.plugins.field.FieldsPlugin"/>
            <!-- 开启支持内存分页   可生成 支持内存分布的方法及参数  
            <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
            -->
            <!-- generate entity时,生成hashcode和equals方法-->
            <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
    
            <!-- 此处是将Example改名为Criteria 当然 想改成什么都行~    -->
            <plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
                <property name="searchString" value="Example$"/>
                <!-- 替换后
                <property name="replaceString" value="Criteria" />
                 -->
                <property name="replaceString" value="Query"/>
            </plugin>
            <!-- 此处是将UserMapper.xml改名为UserDao.xml 当然 想改成什么都行~ -->
            <plugin type="org.mybatis.generator.plugins.rename.RenameSqlMapperPlugin">
                <property name="searchString" value="Mapper"/>
                <property name="replaceString" value="Dao"/>
            </plugin>
            <!-- 此处是将UserMapper改名为UserDao 接口 当然 想改成什么都行~  -->
            <plugin type="org.mybatis.generator.plugins.rename.RenameJavaMapperPlugin">
                <property name="searchString" value="Mapper$"/>
                <property name="replaceString" value="Dao"/>
            </plugin>
    
    
            <commentGenerator type="org.mybatis.generator.plugins.comment.MyCommentGenerator">
                <!-- 是否去除自动生成的注释 true:是 : false:否
                <property name="suppressAllComments" value="true" />
                -->
            </commentGenerator>
    
            <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/pyg" userId="root"
                            password="root">
            </jdbcConnection>
            <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
                connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
                userId="yycg"
                password="yycg">
            </jdbcConnection> -->
    
            <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
                NUMERIC 类型解析为java.math.BigDecimal -->
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
    
    
            <!-- targetProject:生成PO类的位置 -->
            <javaModelGenerator targetPackage="com.alvin.pojo"
                                targetProject=".src">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
                <!-- 从数据库返回的值被清理前后的空格 -->
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
    
            <!-- targetProject:mapper映射文件生成的位置 -->
            <sqlMapGenerator targetPackage="com.alvin.dao"
                             targetProject=".
    esources">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
            </sqlMapGenerator>
            <!-- targetPackage:mapper接口生成的位置 -->
            <javaClientGenerator type="XMLMAPPER"
                                 targetPackage="com.alvin.dao"
                                 targetProject=".src">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="true"/>
            </javaClientGenerator>
    
    
            <!-- 指定数据库表 -->
            <table schema="" tableName="tb_order" domainObjectName="order.Order"/>
            <table schema="" tableName="tb_order_item" domainObjectName="order.OrderItem"/>
            <table schema="" tableName="tb_address" domainObjectName="address.Address"/>
            <table schema="" tableName="tb_areas" domainObjectName="address.Areas"/>
            <table schema="" tableName="tb_cities" domainObjectName="address.Cities"/>
            <table schema="" tableName="tb_provinces" domainObjectName="address.Provinces"/>
            <table schema="" tableName="tb_content" domainObjectName="ad.Content"/>
            <table schema="" tableName="tb_content_category" domainObjectName="ad.ContentCategory"/>
            <table schema="" tableName="tb_pay_log" domainObjectName="log.PayLog"/>
            <table schema="" tableName="tb_seller" domainObjectName="seller.Seller"/>
            <table schema="" tableName="tb_user" domainObjectName="user.User"/>
            <table schema="" tableName="tb_brand" domainObjectName="good.Brand"/>
            <table schema="" tableName="tb_goods" domainObjectName="good.Goods"/>
            <table schema="" tableName="tb_goods_desc" domainObjectName="good.GoodsDesc"/>
            <table schema="" tableName="tb_specification" domainObjectName="specification.Specification"/>
            <table schema="" tableName="tb_specification_option" domainObjectName="specification.SpecificationOption"/>
            <table schema="" tableName="tb_type_template" domainObjectName="template.TypeTemplate"/>
            <table schema="" tableName="tb_freight_template" domainObjectName="template.FreightTemplate"/>
            <table schema="" tableName="tb_item_cat" domainObjectName="item.ItemCat"/>
            <table schema="" tableName="tb_item" domainObjectName="item.Item"/>
            <table schema="" tableName="tb_seckill_goods" domainObjectName="seckill.SeckillGoods"/>
            <table schema="" tableName="tb_seckill_order" domainObjectName="seckill.SeckillOrder"/>
        </context>
    </generatorConfiguration>
    
    
    • javaModelGenerator,生成PO类的位置
    • sqlMapGenerator,mapper映射文件生成的位置
    • javaClientGenerator,mapper接口生成的位置
    • table,指定数据库表

    日志配置
    log4j.properties

    log4j.rootLogger=DEBUG, Console
    #Console
    log4j.appender.Console=org.apache.log4j.ConsoleAppender
    log4j.appender.Console.layout=org.apache.log4j.PatternLayout
    log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
    log4j.logger.java.sql.ResultSet=INFO
    log4j.logger.org.apache=INFO
    log4j.logger.java.sql.Connection=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG
    

    生成

    GeneratorSqlmap.java

    public class GeneratorSqlmap {
    
    	public void generator() throws Exception{
    
    		List<String> warnings = new ArrayList<>();
    		boolean overwrite = true;
    
    		File configFile = new File("generatorConfig.xml");
    		System.out.println(configFile.getAbsolutePath());
    		System.out.println(System.getProperty("user.dir"));
    		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) throws Exception {
    		try {
    			GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
    			generatorSqlmap.generator();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    使用

    select

    // 查询所有
    List<Brand> brandList = brandDao.selectByExample(null);
    
    // 根据id查询
    Brand brand = brandDao.selectByPrimaryKey(id);
    
    // 根据条件拼接查询
    //判断mybatis查询对象
    BrandQuery query = new BrandQuery();
    //拼接sql语句的查询列名
    //query.setFields("name, first_char");
    //设置是否sql语句去除重复数据, 不设置默认是false, 不去重
    //query.setDistinct(true);
    //设置排序
    //query.setOrderByClause("name asc");
    //创建sql语句中的where条件对象
    BrandQuery.Criteria criteria = query.createCriteria();
    //判断条件对象是否为空
    if (brand != null) {
        //判断名称不为空
        if (brand.getName() != null && !"".equals(brand.getName())) {
            criteria.andNameLike("%"+brand.getName()+"%");
        }
        //判断首字母不为空
        if(brand.getFirstChar() != null && !"".equals(brand.getFirstChar())){
            criteria.andFirstCharEqualTo(brand.getFirstChar());
        }
    }
    brandDao.selectByExample(query);
    

    insert

    itemsMapper.insert(items);
    

    update

    //根据主键进行修改, 并且如果传入的参数中有为null的不参与拼接sql语句修改
    brandDao.updateByPrimaryKeySelective(brand);
    
    //根据主键修改, 不管传入对象中的属性是否为null, 都会进行拼接sql语句, 进行修改
    //brandDao.updateByPrimaryKey();
    
    //传入两个参数, 第一个参数: 就是要修改的对象, 第二个参数:是修改条件, 这个条件是非主键条件, 例如根据名称修改等
    //brandDao.updateByExample(, );
    
    //第一个参数是修改对象, 第二个参数:非主键条件, 这个方法修改的时候对于传入的修改对象也会判断是否为null, 进行拼接
    //brandDao.updateByExampleSelective(, )
    

    delete

    brandDao.deleteByPrimaryKey(id);
    
  • 相关阅读:
    【leetcode】92. 反转链表 II
    【leetcode】91. 解码方法
    【leetcode】89. 格雷编码
    【leetcode】86. 分隔链表
    【leetcode】82. 删除排序链表中的重复元素 II
    为什么选择react
    React 全家桶实现后台管理界面
    前后端同构
    浅谈React前后端同构防止重复渲染
    由React引发的前后端分离架构的思考
  • 原文地址:https://www.cnblogs.com/birdofparadise/p/10013154.html
Copyright © 2011-2022 走看看