Mybatis逆向工程

1. 什么是逆向工程

简单的理解,Mybatis逆向工程,就是通过相应插件,自动生成Mybatis数据库连接的一些文件。
Mybatis需要编写sql语句,Mybatis官方提供逆向工程,可以针对单表自动生成Mybatis执行所需要的代码(mapper.java、mapper.xml、pojo…),提高工作效率。

2. 逆向工程的搭建

2.1. 准备数据库

搭建数据库,数据库名、表名和字段名自拟。参考如下:

1111.png

2.2. 搭建Maven工程

这里采用Maven工程,原因是比较方便,不用下载相应的jar包,只需通过在pom.xml文件中引用的形式添加即可。

第一步:创建Maven工程

第二步:在pom.xml文件中,添加Mybatis逆向工程生成器的jar包和数据库连接工具的jar包。

  <!-- 逆向工程生成器 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
        <!-- MySql 连接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

第三步:在工程目录的resources资源目录下创建配置文件,名字自拟。并修改文件为如下内容,参照注释自行修改相关配置。

<?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.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test?serverTimezone=UTC" userId="root"
                        password="5201314">
        </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.demon.pojo"
                            targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.demon.dao"
                         targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.demon.dao"
                             targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table schema="" tableName="teacher"/>
        <table schema="" tableName="student"/>

        <!-- 有些表的字段需要指定java类型
        <table schema="" tableName="">
            <columnOverride column="" javaType="" />
        </table> -->
    </context>
</generatorConfiguration>

第四步:创建执行脚本Main.java,注意File访问路径为配置文件全路径。

public static void main(String[] args){
        try {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            //指定 逆向工程配置文件
            File configFile = new File("D:\\JavaProjects\\reverseproject\\src\\main\\resources\\SqlMapConfig.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);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

第五步:执行脚本Main.java,会自动生成映射文件、接口文件和pojo等,参考工程目录如下:

2222.png

3. 映射文件接口的使用

以上生成的映射文件,下面将根据StudentMapper接口文件分为查找、删除、插入和更新四个板块分别介绍接口的运用,StudentMapper.java接口文件如下:

public interface StudentMapper {
    long countByExample(StudentExample example);

    int deleteByExample(StudentExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    List<Student> selectByExample(StudentExample example);

    Student selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") Student record, @Param("example") StudentExample example);

    int updateByExample(@Param("record") Student record, @Param("example") StudentExample example);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

3.1. 接口使用准备工作

3.1.1 引入jar包

在使用接口文件的时候,必须引用Mybatis的jar包。为了方便测试,这里还引入了测试相关的jar包;采用Spring整合,引入Spring相关jar包;查看日志文件引入log4j的jar包;同时还需要配置资源自动拷贝;最终配置如下:

  <dependencies>
        <!-- 逆向工程生成器 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
        <!-- 数据库连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>
        <!-- 测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!-- 日志处理 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.4</version>
        </dependency>
    </dependencies>

    <build>
        <!-- 如果不配置mybatis的配置文件会漏掉 -->
        <!-- 注意:配置了此方式,原来的默认的资源拷贝行为将无效 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

3.1.2 配置相关文件

配置Spring配置文件ApplicationContext.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
    <!-- 数据源 -->
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost/test?serverTimezone=UTC"/>
    <property name="username" value="root"/>
    <property name="password" value="5201314"/>
    </bean>
    <!-- sqlsessionfactory -->
    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.demon.dao" />
    </bean>

</beans>

配置日志打印文件log4j.properties如下:

log4j.rootLogger=DEBUG,A1

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

3.1.3 添加测试脚本

首先引入@Before注释,初始化ApplicationContext,方便后面使用。

    private ApplicationContext context;

    @Before
    public void initContext() {
        this.context = new ClassPathXmlApplicationContext("classpath:ApplicationContext.xml");
    }

最终工程目录截图如下:

2222.png

3.2. 查找接口使用

countByExample顾名思义是,通过StudentExample的筛选条件完成搜索结果个数的统计,参考代码如下:

@Test
    public void testCountByExample() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        StudentExample studentExample = new StudentExample();
        //设置查询条件,不设置则全部查询
        Criteria criteria = studentExample.createCriteria();
        criteria.andIdGreaterThanOrEqualTo(2);

        long number = studentMapper.countByExample(studentExample);
        System.out.println(number);
    }

selectByExample通过StudentExample的筛选条件完成搜索结果,并返回Student的List对象。

@Test
    public void testSelectByExample() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        StudentExample studentExample = new StudentExample();
        //设置查询条件,必须同时满足
//        Criteria criteria = studentExample.createCriteria();
//        criteria.andSexEqualTo(2);
//        criteria.andNameLike("Demon");

        //设置查询条件,满足一个条件即可
        Criteria criteria = studentExample.createCriteria();
        criteria.andSexEqualTo(2);
        Criteria criteria1 = studentExample.or();
        criteria1.andNameLike("Demon");

        List<Student> studentList = studentMapper.selectByExample(studentExample);
        for (Student student:studentList) {
            System.out.println(student.getId());
        }
    }

selectByPrimaryKey,根据主键返回Student对象。

@Test
    public void testSelectByPrimaryKey() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        Student student = studentMapper.selectByPrimaryKey(2);
        System.out.println(student.getName());
    }

3.3. 插入接口使用

insert,直接插入Student对象,插入成功返回1。

@Test
    public void testInsert() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        Student student = new Student();
        student.setName("Demon");
        student.setSex(1);
        int result = studentMapper.insert(student);
        System.out.println(result);
    }

insertSelective,直接插入Student对象,插入成功返回1。 而与insert不同的是,他只会插入含有数据的属性,对于为空的属性,不予以处理,这样的话如果数据库中设置有默认值,就不会被空值覆盖。

@Test
    public void testInsertSelective() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        Student student = new Student();
        student.setName("Demon");
        int result = studentMapper.insertSelective(student);
        System.out.println(result);
    }

3.4. 更新接口使用

updateByExample,这个接口由两个参数一个Student,一个StudentExample。第一个是要更新的内容,注意如果数据库字段中有不能为空的,一定要在这里设置,不然会报错的,比如id;第二个参数是需要更新的筛选项。

@Test
    public void testUpdateByExample() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        Student student = new Student();
        student.setName("Demon222");
        student.setSex(1);
        student.setId(1);

        StudentExample studentExample = new StudentExample();
        Criteria criteria = studentExample.createCriteria();
        criteria.andIdEqualTo(30);

        int result = studentMapper.updateByExample(student,studentExample);
        System.out.println(result);
    }

updateByExampleSelective,主要区别于updateByExample的是设置项可以为空,当为空时,不改变原有值,应用比较广泛。

@Test
    public void testUpdateByExampleSelective() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        Student student = new Student();
        student.setName("Demon333");
        student.setSex(1);

        StudentExample studentExample = new StudentExample();
        Criteria criteria = studentExample.createCriteria();
        criteria.andIdEqualTo(30);

        int result = studentMapper.updateByExampleSelective(student,studentExample);
        System.out.println(result);
    }

updateByPrimaryKey,通过主键更新,可以直接创建新对象进行更新,但是数据库中不能为空的值,一定要设置,不然会报错。也可以先通过主键获取对象,修改之后再更新。建议使用后者。

@Test
    public void testUpdateByPrimaryKey() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        Student student = studentMapper.selectByPrimaryKey(22);
        student.setName("Demon555");
        student.setSex(1);

        int result = studentMapper.updateByPrimaryKey(student);
        System.out.println(result);
    }

updateByPrimaryKeySelective,而与updateByPrimaryKey不同的是,他只会更新含有数据的属性,对于为空的属性,不予以处理,这样的话如果数据库中设置有默认值,就不会被空值覆盖。

@Test
    public void testUpdateByPrimaryKeySelective() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        Student student = studentMapper.selectByPrimaryKey(22);
        student.setName("Demon666");
        student.setSex(1);

        int result = studentMapper.updateByPrimaryKeySelective(student);
        System.out.println(result);
    }

3.5. 删除接口使用

deleteByExample,根据筛选条件,删除对象。返回值为删除对象个数。

@Test
    public void testDeleteByExample() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);
        StudentExample studentExample = new StudentExample();
        //添加条件把模糊查询Demon的数据全部删除
        Criteria criteria = studentExample.createCriteria();
        criteria.andNameLike("%Demon%");

        int result = studentMapper.deleteByExample(studentExample);
        System.out.println(result);
    }

deleteByPrimaryKey,根据主键删除对象,如果没有对应主键,返回为0;否在返回为1。

@Test
    public void testDeleteByPrimaryKey() {
        StudentMapper studentMapper = context.getBean(StudentMapper.class);

        int result = studentMapper.deleteByPrimaryKey(2);
        System.out.println(result);
    }

文档下载地址:

https://wenku.baidu.com/view/a7f30fc8961ea76e58fafab069dc5022aaea466b

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念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