Mybatis笔记(三):逆向工程

[toc]

概述

  1. 官网提供的mapper自动生成工具mybatis-generator-core-1.3.6.jar
  2. 可以生成 po类,mapper映射文件,mapper接口
  3. 支持单表查询(简单查询,条件查询,1.3.6提供动态sql)
  4. 官网MyBatis Generator使用文档:http://www.mybatis.org/generator/index.html

mybatis-generator逆向工程

如何搭建

  • jar包

    • log4j
    • mybatis核心
    • mybatis-generator-core-1.3.6.jar
    • 数据库连接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>
                <!-- 是否 去除自动生成的注释 true:是 : false:否 -->
                <property name="suppressAllComments" value="true" />
            </commentGenerator>
    
            <!--数据库连接 信息-->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://10.211.55.6:3306/mybatis?characterEncoding=utf-8"
                            userId="machine"
                            password="4869">
            </jdbcConnection>
    
            <!-- 如使用oracle参考如下 -->
            <!--
            <jdbcConnection
                driverClass="oracle.jdbc.driver.OracleDriver"
                connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:orcl"
                userId="scott"
                password="wcy675600920">
            </jdbcConnection> -->
    
            <!--
                false(默认): 把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,
                true: 把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal
            -->
            <javaTypeResolver >
                <property name="forceBigDecimals" value="false" />
            </javaTypeResolver>
    
            <!--targetProject: 生成 PO类 的位置-->
            <!--
                mac下路径是./src
                windows 路径是.\src
            -->
            <javaModelGenerator targetPackage="com.machine.pro.pojo" targetProject="./src">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false" />
                <!-- 从数据库返回的值 被清理前后的空格 -->
                <property name="trimStrings" value="true" />
            </javaModelGenerator>
    
            <!-- targetProject: 生成 mapper映射文件 的位置 -->
            <sqlMapGenerator targetPackage="com.machine.pro.mapper"  targetProject="./src">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false" />
            </sqlMapGenerator>
    
            <!-- targetPackage:mapper接口生成的位置 -->
            <javaClientGenerator type="XMLMAPPER" targetPackage="com.machine.pro.mapper"  targetProject="./src">
                <!-- enableSubPackages:是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false" />
            </javaClientGenerator>
    
    
            <!--指定要生成的 数据库表-->
            <table tableName="user" />
            <table tableName="orders" />
    
            <!--table更多细节-->
            <!--
            <table tableName="" domainObjectName="">
               <columnOverride column="" javaType="" />
            </table>
            -->
        </context>
    </generatorConfiguration>
    
    
  • GeneratorSqlMap.java

    public class GeneratorSqlMap {
    
        public void generator() throws Exception{
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            //指定逆向工程配置文件
            File configFile = new File("config/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 generator = new GeneratorSqlMap();
                generator.generator();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
  • 运行main可生成相应代码

附录:我的代码地址

https://github.com/Machine4869/MyCode/tree/master/Mybatis逆向工程/

一些映射 生成规则

  • 如表的creat_time字段 会映射成 pojo的craeteTime属性(去下划线大写)
  • user表 会映射成 User类
  • tb_user表会映射成 TbUser类

Mapper接口测试与使用

(法一)采用Example进行条件查询

配置:targetRuntime="MyBatis3"

<context id="testTables" targetRuntime="MyBatis3">

常用接口

//按id 查询
UserselectByPrimaryKey(String id);
//按id 删除
int deleteByPrimaryKey(String id);
//按id 更新:对象中所有字段
int updateByPrimaryKey(User record);
//按id 更新:对象中非空字段
int updateByPrimaryKeySelective(User record);

//插入对象 所有字段
//  :insert into user(id,username,sex....) values..
int insert(User record);
//插入对象 非空字段
//  :insert into user(username) values..
int insertSelective(User record);

//按条件 删除
int deleteByExample(UserExample example);

//按条件 查询 结果集
List<User> selectByExample(UserExample example);

条件查询:

@Test
public void test3(){
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

    //查询所有
    /*
    UserExample userExample = null;
    List<User> userList = userMapper.selectByExample(userExample);
    */

    //单条件查询
    /*
    UserExample userExample = new UserExample();
    UserExample.Criteria criteria = userExample.createCriteria();
    criteria.andUsernameLike("%m%");
    List<User> userList = userMapper.selectByExample(userExample);
    */

    //多条件查询and
    /*
    UserExample userExample = new UserExample();
    UserExample.Criteria criteria = userExample.createCriteria();
    criteria.andUsernameLike("%m%");
    criteria.andSexEqualTo("女");
    List<User> userList = userMapper.selectByExample(userExample);
    */

    //多条件查询or
    /*
    UserExample userExample = new UserExample();

    UserExample.Criteria criteria1 = userExample.createCriteria();
    criteria1.andUsernameLike("%m%");

    UserExample.Criteria criteria2 = userExample.createCriteria();
    criteria2.andSexEqualTo("女");

    userExample.or(criteria1);
    userExample.or(criteria2);

    List<User> userList = userMapper.selectByExample(userExample);
    */

    //排序
    /*
    UserExample userExample = new UserExample();

    UserExample.Criteria criteria = userExample.createCriteria();
    criteria.andUsernameLike("%m%");

    //userExample.setOrderByClause("id asc");//asc:正序排 desc:逆序排
    //userExample.setOrderByClause("id desc");
    userExample.setOrderByClause("sex asc,username asc");

    List<User> userList = userMapper.selectByExample(userExample);
    */

    //统计
    /*
    UserExample userExample = new UserExample();
    UserExample.Criteria criteria = userExample.createCriteria();

    criteria.andUsernameLike("%m%");
    criteria.andIdBetween(1,5);//包括1和5

    long count = userMapper.countByExample(userExample);
    */
    
}

(法二)MyBatis Dynamic SQL(用where子句进行条件查询)

  1. 概述:

    • generator 使用为MyBatis3DynamicSQL生成代码,这些类依赖于MyBatis Dynamic SQL
    • MyBatis Dynamic SQL 是生成动态 SQL 语句的框架,可以配合为MyBatis Generator使用
    • MyBatis Dynamic SQL 使用WHERE子句(可以用任意组合的and和or来创建)进行条件查询
    • MyBatis Dynamic SQL lib下载地址
  2. 准备工作

使用:

前提:import静态支持类

import static com.machine.pro.mapper.UserDynamicSqlSupport.*;  // import 自动生成的 "support" 类
import static org.mybatis.dynamic.sql.SqlBuilder.*;  // import MyBatis Dynamic SQL where support

使用案例:

@Test
public void test2(){
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    /**
     * MyBatis Dynamic SQL
     * build():所有构建器都通过调用build()方法完成
     * execute():调用execute方法执行语句
     */
    //按主键查询 仍然可用
    /*
    User user = userMapper.selectByPrimaryKey(3);
    */

    //查询所有(不用where子句)
    /*
    List<User> userList = userMapper.selectByExample()
            .build().execute();
    */

    //单条件查询
    /*
    List<User> userList = userMapper.selectByExample()
            .where(sex, isEqualTo("女"))
            .build().execute();
            //如sex属性就来自import static 的支持类
    */

    //多条件查询and
    /*
    List<User> userList = userMapper.selectByExample()
            .where(sex, isEqualTo("女"))
            .and(username, isLike("%m%"))
            .build().execute();
    */

    //多条件查询or
    /*
    List<User> userList = userMapper.selectByExample()
            .where(sex, isEqualTo("女"))
            .or(username, isLike("%m%"))
            .build().execute();
    */

    //排序:正序
    /*
    List<User> userList = userMapper.selectByExample()
            .where(username, isLike("%m%"))
            .orderBy(id)
            .build().execute();
    */

    //排序:逆序
    /*
    List<User> userList = userMapper.selectByExample()
            .where(username, isLike("%m%"))
            .orderBy(id.descending())
            .build().execute();
    */

    //排序:多字段
    /*
    List<User> userList = userMapper.selectByExample()
            .where(username, isLike("%m%"))
            .orderBy(sex.descending(),username)
            .build().execute();
    */

    //统计
    /*
    Long count = userMapper.countByExample()
            .build().execute();
    */
}

注意事项

Mapper文件内容不覆盖而是追加

  • XXXMapper.xml文件已经存在时,如果进行重新生成则mapper.xml文件内容不被覆盖而是进行内容追加,结果导致mybatis解析失败。
  • 解决方法:删除原来已经生成的mapper xml文件再进行生成。

针对oracle数据库的 Table schema问题

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • MyBatis Generator (MBG) 是由一个XML配置文件驱动的。这个配置文件中会声明以下内容: 如何...
    JSON_NULL阅读 19,157评论 3 10
  • 今天培训课堂上老师给我们分享了一个支教的小故事,我这人一向泪点就低,没有看到场景光听老师描述就感动的出眼泪了,而...
    云沐妈妈阅读 396评论 0 1
  • 我是一个喜欢说话的人。并非天性喜欢说话,而是在年少时,因为种种原因,没能和同龄人说够话。确切地说,自五年级起,到中...
    郭国酬阅读 3,920评论 1 3
  • 电脑里放着绿色花园,轻音乐,我曾经在电台做节目时候的背景音乐。电脑旁边是十月文艺出版的安妮宝贝十年文集,...
    水墨清欢阅读 318评论 2 1
  • 将来有一天后,肯定会变成一个合格的社会人吧;但从那一天起,肯定不会再踏入学校半步。
    古道尘绝阅读 281评论 3 2

友情链接更多精彩内容