Mybatis(八)逆向工程

     mybaits需要程序员自己编写sql语句,mybatis官方提供逆向工程,可以本着单表自动生成mybatis执行所急需的代码(mapper.java,mapper.xml、pojo等)有矣sql表的组织后, 我们便足以采用逆向工程一直扭转对应的Dao和JavaBean代码, 以及mapper.xml文件,这样能够大大减少我们平常支付之工作量。
但是下逆向工程局限性, 逆向工程措施就会实施同样软, 如果再次实施就会持续生成对应的Dao和JavaBean, 除非我们将前生成的皆删除。这样对于代码的扩展性就不是雅好, 如果我们要对表结构进行修改, 那么我们虽亟须对转移的Dao和JavaBean进行一个个修改,或者另行生成一份。

     MyBatis Generator:简称MBG,是一个特意为MyBatis框架使用者定制的代码生成器,可以快的基于表生成对应的映射文件,接口,以及bean类。支持中心的增删改查,以及QBC风格的法查询。但是表连接、
存储过程相当这些扑朔迷离sql的概念需要我们手工编制。

 文档查阅:

http://www.mybatis.org/generator/

官网下载:

https://github.com/mybatis/

下载步骤如下:

      图片 1

 

 

        图片 2

        图片 3

  使用手续:

  1、导入相关的jar包:这里支持mysql,oracl

    图片 4

 

  2、编写MBG的布置文件(重要几地处安排)

  1)jdbcConnection配置数据库连接信息

  2)javaModelGenerator配置javaBean的变动策略

  3)sqlMapGenerator 配置sql映射文件生成策略

  4)javaClientGenerator配置Mapper接口的变更策略

  5)table 配置要逆向分析的数据表(tableName:表名,domainObjectName:对应之javaBean名)

  运行代码生成器生成代码注意Context标签,targetRuntime=“MyBatis3“可以生成带条件的增删改查,targetRuntime=“MyBatis3Simple“可以转变基本的增删改查,如果重转移,建议以事先生成的数额删除,避免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>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://192.168.61.22:3306/test" userId="root"
            password="123456">
        </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.softjx.model"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.softjx.dao" 
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>


        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.softjx.dao" 
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>


        <!-- 指定数据库表 -->
<table schema="test" tableName="school" domainObjectName="School"></table>
        <table schema="test" tableName="student" domainObjectName="Student"></table>    

    </context>
</generatorConfiguration>

  3、编译生成代码

  

import java.io.File;
import java.io.IOException;
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.exception.XMLParserException;
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) throws Exception {
        try {
            GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

  4、导入用工具转pojo,mapper.xml,接口文件,编写测试代码。

 

    //测试    
    @Test
    public void TestGetStudent() throws IOException {
        try {        
            StudentMapper mapper=session.getMapper(StudentMapper.class);
            System.out.println(mapper);
            Student student=mapper.selectByPrimaryKey(3);

            System.out.println(student.gettId() + "   " + student.gettName() + "  "+student.gettAge()+" "+student.gettEnterdate()+"  "+student.gettSid());


          } finally {
        session.close();
    }

    }



    //测试    (复杂条件测试)
        @Test
        public void TestGetStudent1() throws IOException {
            try {        
                StudentMapper mapper=session.getMapper(StudentMapper.class);
                System.out.println(mapper);

                //1.查询所有:
                /*
                StudentExample example=null;
                List<Student> students=mapper.selectByExample(example);
                for(Student student :students)
                System.out.println(student.gettId() + "   " + student.gettName() + "  "+student.gettAge()+" "+student.gettEnterdate()+"  "+student.gettSid());
                 */


                //2.单个条件查询:
                /*
                StudentExample example=new StudentExample();
                Criteria criteria= example.createCriteria();
                criteria.andTAgeGreaterThan(60);                
                List<Student> students=mapper.selectByExample(example);
                for(Student student :students)
                System.out.println(student.gettId() + "   " + student.gettName() + "  "+student.gettAge()+" "+student.gettEnterdate()+"  "+student.gettSid());
                */


                //3.多条件查询and:
                /*
                StudentExample example=new StudentExample();
                Criteria criteria= example.createCriteria();
                criteria.andTAgeGreaterThan(20);
                criteria.andTNameLike("%g%");

                List<Student> students=mapper.selectByExample(example);
                for(Student student :students)
                System.out.println(student.gettId() + "   " + student.gettName() + "  "+student.gettAge()+" "+student.gettEnterdate()+"  "+student.gettSid());
               */


                //4.多条件查询or:
                 /*
                StudentExample example=new StudentExample();
                Criteria criteria= example.createCriteria();
                criteria.andTAgeGreaterThan(20);
                criteria.andTNameLike("%g%");                
                Criteria criteria1= example.createCriteria();
                criteria1.andTSidLessThanOrEqualTo(1);                
                example.or(criteria1);                
                List<Student> students=mapper.selectByExample(example);
                for(Student student :students)
                System.out.println(student.gettId() + "   " + student.gettName() + "  "+student.gettAge()+" "+student.gettEnterdate()+"  "+student.gettSid());

             */

                //5.排序:
                /*
                StudentExample example=new StudentExample();
                Criteria criteria= example.createCriteria();
                criteria.andTAgeGreaterThan(20);
                criteria.andTNameLike("%g%");

                Criteria criteria1= example.createCriteria();
                criteria1.andTSidLessThanOrEqualTo(1);                
                example.or(criteria1);    

                //example.setOrderByClause("t_id desc");

                example.setOrderByClause("t_age desc,t_id asc");

                List<Student> students=mapper.selectByExample(example);
                for(Student student :students)
                System.out.println(student.gettId() + "   " + student.gettName() + "  "+student.gettAge()+" "+student.gettEnterdate()+"  "+student.gettSid());
                */


                //6.统计
                StudentExample example=new StudentExample();
                Criteria criteria= example.createCriteria();
                //criteria.andTAgeGreaterThan(60);

                criteria.andTAgeGreaterThan(60);
                criteria.andTNameLike("%g%");

                int count=mapper.countByExample(example);
                 System.out.println(count);

              } finally {
            session.close();
        }

        }

 

网站地图xml地图