Mybatis逆向工程

1. 介绍

Mybatis是目前非常流行的持久层框架,其逆向工程更是大大缩减了我们的开发时间。

所谓mybatis逆向工程,就是Mybatis会根据我们设计好的数据表,自动生成pojo(实体)mapper(接口)以及mapper.xml(映射)

而且会在文件中给我们生成单表增删改查的方法和sql

image-20201211164421070

2. 插件使用

2.1 引入依赖 mybatis-generator

    <dependencies>
          <!--必要-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
         <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--非必要-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
              <!--mybatis-generator的Maven插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

2.2 加入配置文件

将资料包下的generatorConfig.xml 拷贝到 项目的resouces下

2.2.1 文件名称:generratorConfig.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>
    <!-- classPathEntry:数据库的 JDBC驱动的jar 包地址 -->
    <classPathEntry location="lib/mysql-connector-java-5.1.47.jar"/>

    <!--生成java代码-->
    <context id="context" targetRuntime="MyBatis3">

        <!-- 配置生成pojo的序列化的插件-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

        <!-- 配置生成toString的序列化的插件  -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

        <commentGenerator>
            <!-- 是否去除自动生成的(english)注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/spring_141"
                        userId="root"
                        password="root"/>

        <!-- 指定生成的实体类的存放位置 -->
        <javaModelGenerator targetPackage="com.itheima.domain" targetProject="./src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 指定生成的Dao映射文件的存放位置 -->
        <sqlMapGenerator targetPackage="com.itheima.dao" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!--指定生成的Dao接口的存放位置-->
        <javaClientGenerator targetPackage="com.itheima.dao" targetProject="./src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 指定数据库表 -->
        <table tableName="account" domainObjectName="Account" mapperName="AccountDao"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="true" enableUpdateByExample="false"/>

    </context>
</generatorConfiguration>

拷贝测试用配置文件

2.2.2 文件名称:mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--数据库环境信息-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///spring"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--mapper映射文件-->
    <mappers>
        <package name="com.itheima.dao"/>
    </mappers>
</configuration>
image-20210609092556130

2.2.3 手动加入mysql-connector的jar包

image-20210816161734200

2.3 运行插件,生成文件

image-20201220115506038

3. 生成的文件的使用

3.1 基础操作

public interface AccountDao {
    //保存
    int insert(Account record);

    //动态sql的保存
    int insertSelective(Account record);

    //主键修改
    int updateByPrimaryKey(Account record);

    //动态sql的主键修改
    int updateByPrimaryKeySelective(Account record);

    //根据主键删除
    int deleteByPrimaryKey(Integer aid);

    //主键查询
    Account selectByPrimaryKey(Integer aid);

    //条件查询
    List<Account> selectByExample(AccountExample example);
}

3.2 条件查询

模板代码,直接复制使用即可

public class MyBatisTest {
    private SqlSession sqlSession;

    @Before
    public void getSqlSession() {
        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
        sqlSession = factory.openSession(true);
    }

    @After
    public void closeSqlSession() {
        sqlSession.close();
    }

    @Test
    public void test1() {
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        AccountExample example = new AccountExample();

    }
}

引入配置文件,修改数据库配置信息

[图片上传失败...(image-3d2362-1629158952976)]

测试代码

package com.itheima.test;

import com.itheima.dao.AccountDao;
import com.itheima.domain.AccountExample;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/*
    AccountExample 这哥们有三个功能
    1 条件查询
        example.createCriteria().条件
    2 排序
       example.setOrderByClause(排序条件) 
    3 去重
        example.setDistinct(true);
*/
public class MybatisTest {
    private SqlSession sqlSession;

    @Before
    public void getSqlSession() {
        InputStream stream = null;
        try {
            stream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
        sqlSession = factory.openSession(true);
    }

    @After
    public void closeSqlSession() {
        sqlSession.close();
    }

    @Test
    public void test1() {
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        AccountExample example = new AccountExample();

        //这是example的一个小弟,作用是用于条件的拼接
        AccountExample.Criteria criteria = example.createCriteria();
//        criteria.andAidGreaterThan(2);//where aid > 2
//        criteria.andBalanceBetween(10f,100f);//WHERE ( aid > 2 and balance between 1 and 100 )
//        criteria.andNameLike("B%");//WHERE ( aid > ? and balance between ? and ? and name like B% )

        criteria.andAidGreaterThan(2).andBalanceBetween(10f, 100f).andNameLike("B%");

        accountDao.selectByExample(example);
    }


    @Test
    public void test2() {
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        AccountExample example = new AccountExample();

        //这是example的一个小弟,作用是用于排序
        example.setOrderByClause("aid desc");//from account order by aid desc
        accountDao.selectByExample(example);
    }

    @Test
    public void test3() {
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        AccountExample example = new AccountExample();

        //这是example的一个小弟,作用是用于去重
        example.setDistinct(true);
        accountDao.selectByExample(example);
    }
} 

3.3 模板说明

* 条件说明
* criteria.andXxxIsNull    添加字段xxx为null的条件
* criteria.andXxxIsNotNull    添加字段xxx不为null的条件
* criteria.andXxxEqualTo(value)    添加xxx字段等于value条件
* criteria.andXxxNotEqualTo(value)    添加xxx字段不等于value条件
* criteria.andXxxGreaterThan(value)    添加xxx字段大于value条件
* criteria.andXxxGreaterThanOrEqualTo(value)    添加xxx字段大于等于value条件
* criteria.andXxxLessThan(value)    添加xxx字段小于value条件
* criteria.andXxxLessThanOrEqualTo(value)    添加xxx字段小于等于value条件
* criteria.andXxxIn(List<?>)    添加xxx字段值在List<?>条件
* criteria.andXxxNotIn(List<?>)    添加xxx字段值不在List<?>条件
* criteria.andXxxLike(“%”+value+”%”)    添加xxx字段值为value的模糊查询条件
* criteria.andXxxNotLike(“%”+value+”%”)    添加xxx字段值不为value的模糊查询条件
* criteria.andXxxBetween(value1,value2)    添加xxx字段值在value1和value2之间条件
* criteria.andXxxNotBetween(value1,value2)    添加xxx字段值不在value1和value2之间条件
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,110评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,443评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,474评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,881评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,902评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,698评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,418评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,332评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,796评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,968评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,110评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,792评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,455评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,003评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,130评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,348评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,047评论 2 355

推荐阅读更多精彩内容