【Spring+Mybatis+SpringMVC整合项目三】天猫商城(逆向工程)

本文介绍MyBatis逆向工程功能,通过已有数据库表结构快速生成POJO、Mapper和XML文件,提升开发效率,降低错误率。文章详细展示了generatorConfig.xml配置文件的设置,包括代码注释、数据库连接、文件存放位置等,并提供了MybatisGenerator.java示例,展示如何运行生成代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybatis为我们带来了强大的逆向工程功能,在已有的数据库表结构基础上,利用逆向工程可以快速生成pojo,mapper,xml这些文件,减少我们写代码的工作,同时降低出错率。

 

首先在resources目录下配置好generatorConfig.xml文件

1.在生成的代码中,不提供注释。如果提供注释,生成出来的代码,看上去乱七八糟的。

<commentGenerator>

2.指定链接数据库的账号和密码,既然是逆向工程,肯定要先链接到数据库才对啊

<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/tmall_ssm" userId="root" password="admin">

3.指定生成的pojo,mapper, xml文件的存放位置

        <!--生成pojo类存放位置-->
        <javaModelGenerator targetPackage="com.how2java.tmall.pojo" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成xml映射文件存放位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成mapper类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.how2java.tmall.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

 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="DB2Tables"    targetRuntime="MyBatis3">
        
        <!--是否在代码中显示注释-->
        <commentGenerator>
            <property name="suppressDate" value="true" />
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
 
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/tmall_ssm" userId="root" password="admin">
        </jdbcConnection>
        <!--不知道做什么用的。。。反正贴上来了~-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--生成pojo类存放位置-->
        <javaModelGenerator targetPackage="com.how2java.tmall.pojo" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成xml映射文件存放位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成mapper类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.how2java.tmall.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
 
        <!--生成对应表及类名-->
 
        <table tableName="category" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
            <property name="my.isgen.usekeys" value="true"/>
            <property name="useActualColumnNames" value="true"/>
            <generatedKey column="id" sqlStatement="JDBC"/>
 
        </table>
 
       <table tableName="property" domainObjectName="Property" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
                    <property name="my.isgen.usekeys" value="true"/>
                    <property name="useActualColumnNames" value="true"/>
                    <generatedKey column="id" sqlStatement="JDBC"/>
       </table>
 
       <table tableName="product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
                    <property name="my.isgen.usekeys" value="true"/>
                    <property name="useActualColumnNames" value="true"/>
                    <generatedKey column="id" sqlStatement="JDBC"/>
     </table>
 
                <table tableName="productImage" domainObjectName="ProductImage" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
                    <property name="my.isgen.usekeys" value="true"/>
                    <property name="useActualColumnNames" value="true"/>
                    <generatedKey column="id" sqlStatement="JDBC"/>
                </table>
 
                <table tableName="order_" domainObjectName="Order" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
                    <property name="my.isgen.usekeys" value="true"/>
                    <property name="useActualColumnNames" value="true"/>
                    <generatedKey column="id" sqlStatement="JDBC"/>
                </table>
 
                <table tableName="propertyValue" domainObjectName="PropertyValue" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
                    <property name="my.isgen.usekeys" value="true"/>
                    <property name="useActualColumnNames" value="true"/>
                    <generatedKey column="id" sqlStatement="JDBC"/>
                </table>
 
                <table tableName="review" domainObjectName="Review" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
                    <property name="my.isgen.usekeys" value="true"/>
                    <property name="useActualColumnNames" value="true"/>
                    <generatedKey column="id" sqlStatement="JDBC"/>
                </table>
 
                <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
                    <property name="my.isgen.usekeys" value="true"/>
                    <property name="useActualColumnNames" value="true"/>
                    <generatedKey column="id" sqlStatement="JDBC"/>
                </table>
 
                <table tableName="orderItem" domainObjectName="OrderItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
                    <property name="my.isgen.usekeys" value="true"/>
                    <property name="useActualColumnNames" value="true"/>
                    <generatedKey column="id" sqlStatement="JDBC"/>
                </table>
      
    </context>
</generatorConfiguration>

然后,准备一个MybatisGenerator.java,这个类运行之后即可生成pojo,mapper和xml文件。

package com.how2java.tmall.util;
 
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
public class MybatisGenerator {
 
    public static void main(String[] args) throws Exception {
        String today = "2017-10-14";
 
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        Date now =sdf.parse(today);
        Date d = new Date();
 
        if(d.getTime()>now.getTime()+1000*60*60*24){
            System.err.println("——————未成成功运行——————");
            System.err.println("——————未成成功运行——————");
            System.err.println("本程序具有破坏作用,应该只运行一次,如果必须要再运行,需要修改today变量为今天,如:" + sdf.format(new Date()));
            return;
        }
 
        if(false)
            return;
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        InputStream is= MybatisGenerator.class.getClassLoader().getResource("generatorConfig.xml").openStream();
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
 
        System.out.println("生成代码成功,只能执行一次,以后执行会覆盖掉mapper,pojo,xml 等文件上做的修改");
 
    }
}

运行上面的MybatisGenerator.java,然后看看

 

mybatis已经帮我们生成好了,我们只需要在上面略做修改,就能满足我们的开发需要 了

而我们可以发现,pojo下面,会多出一些名为XXXExample的类,这些类是我们做条件查询时候要用到的,有了这些类,我们做条件查询时候就不用额外去写sql语句,简化了开发流程。比如

我们要根据一个用户的id来查询这个用户下的所有订单,可以这样做

 @Override
    public List<Order> list(int uid, String excludedStatus) {
        OrderExample example=new OrderExample();
        example.createCriteria().andUidEqualTo(uid);
        example.setOrderByClause("id desc");
        List<Order> os=orderMapper.selectByExample(example);
        return os;
    }

当然,如果是要追求性能的话,还是建议大家自己写sql语句。

以上就是mybatis三剑客之一的逆向工程。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值