java web 之mybatis使用教程(十一)

逆向工程生成代码

1. 什么是逆向工程

mybatis的一个主要的特点就是需要程序员自己编写sql,那么如果表太多的话,难免会很麻烦,所以mybatis官方提供了一个逆向工程,可以针对单表自动生成mybatis执行所需要的代码(包括mapper.xml、mapper.java、po..)。一般在开发中,常用的逆向工程方式是通过数据库的表生成代码。

2. 使用逆向工程

通过IDEA新建一个maven java工程。

修改pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.cx</groupId>
  <artifactId>mybatisgenerator</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>mybatisgenerator</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.6</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
      <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-core</artifactId>
          <version>1.3.5</version>
      </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>

          <plugin>
              <groupId>org.mybatis.generator</groupId>
              <artifactId>mybatis-generator-maven-plugin</artifactId>
              <version>1.3.5</version>
              <configuration>
                  <verbose>true</verbose>
                  <overwrite>true</overwrite>
              </configuration>
          </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

整个目录:

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>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatisdemo" 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.cx.pojo"
                            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置,重要!! -->
        <sqlMapGenerator targetPackage="com.cx.mapper"
                         targetProject=".\src">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置,重要!! -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.cx.mapper"
                             targetProject=".\src">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表,要生成哪些表,就写哪些表,要和数据库中对应,不能写错! -->
        <table tableName="items"></table>
        <table tableName="orders"></table>
        <table tableName="orderdetail"></table>
        <table tableName="user"></table>
    </context>
</generatorConfiguration>

配置文件主要要做的几件事是: 

  1. 连接数据库,这是必须的,要不然怎么根据数据库的表生成代码呢?
  2. 指定要生成代码的位置,要生成的代码包括po类, mapper.xml和mapper.java
  3. 指定数据库中想要生成哪些表

GeneratorSqlmap.java类:

package com.cx;

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.File;
import java.util.ArrayList;
import java.util.List;

public class GeneratorSqlmap {
    public void generator() throws Exception{

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        //指向逆向工程配置文件
        File configFile = new File("src/main/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();
        }

    }
}

运行GeneratorSqlmap。然后就会生成文件,如下:

每个po类多了一个东西,就是xxxExample.java,这个类是给用户自定义sql是用的。然后把生成的文件拷贝到自己的工程里,这里我们拷贝ItemsMapper.java/ItemsMapper.xml/Items.java/ItemsExample.java。

测试代码:

@Test
    public void testItemInsert() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ItemsMapper itemsMapper = sqlSession.getMapper(ItemsMapper.class);

        Items items = new Items();
        items.setName("手机");
        items.setPrice(5000f);
        items.setCreatetime(new Date());
        itemsMapper.insert(items);
        sqlSession.commit();
        //还有一个insertSelective(items);方法,是插入的项不为空时,才将那个字段拼接到sql中
        //可以下自动生成的xml文件就知道了。
    }

    //自定义查询
    @Test
    public void testSelectByExample() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ItemsMapper itemsMapper = sqlSession.getMapper(ItemsMapper.class);

        //自定义查询,这就用到了ItemsExample类了,里面有个Criteria内部类,专门用来封装自定义查询条件的
        ItemsExample itemsExample = new ItemsExample();
        ItemsExample.Criteria criteria = itemsExample.createCriteria();
        //andNameEqualTo相当于在sql中拼接一个“AND name='背包'”
        //还有其他很多方法,都是用来自定义查询条件的,可以自己看一下不同的方法
        criteria.andNameEqualTo("背包");
        List<Items> itemsList = itemsMapper.selectByExample(itemsExample);
        System.out.println(itemsList);
    }

    //根据主键查询,跟原来一样
    @Test
    public void testSelectByPrimaryKey() {
        ItemsMapper itemsMapper = sqlSessionFactory.openSession().getMapper(ItemsMapper.class);
        Items items = itemsMapper.selectByPrimaryKey(1);
        System.out.println(items);
    }

    //根据主键更新item,跟原来一样
    @Test
    public void testUpdateByPrimaryKey() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ItemsMapper itemsMapper = sqlSession.getMapper(ItemsMapper.class);
        Items items = itemsMapper.selectByPrimaryKey(1);
        items.setPrice(3540f);
        itemsMapper.updateByPrimaryKey(items);
        sqlSession.commit();
    }

 逆向工程生成的代码,基本上和之前使用的差不多,只不过它更规范一点,而且还多了自定义查询条件的java类,用起来还是挺方便的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值