逆向工程

1. 首先我们需要知道什么是逆向工程

mybatis逆向工程简称MBG。它是专门为MyBatis框架使用者定制的代码生成器。
可以快速的根据表生成对应的映射文件接口,以及Bean类对象

逆向工程只能对单表生成CRUD操作
它可以帮我们对比数据库表之后,生成大量的这个基础代码。
这些基础代码有:
1、数据库表对应的javaBean对象
2、这些javaBean对象对应的Mapper接口
3、这些Mapper接口对应的配置文件

  	<!-- 去掉全部的注释 -->
	<commentGenerator>
        <property name="suppressAllComments" value="true" />
    </commentGenerator>

准备数据库表

create database mbg;
use mbg;

create table t_user(
	`id` int primary key auto_increment, /*主键自增*/
	`username` varchar(30) not null unique,/*用户名非空且唯一*/
	`password` varchar(40) not null,/*密码非空*/
	`email` varchar(50)/*邮箱*/
);

insert into t_user(`username`,`password`,`email`) values('admin','admin','[email protected]');
insert into t_user(`username`,`password`,`email`) values('wzg168','123456','[email protected]');

create table t_book(
	`id` int primary key auto_increment,
	`name` varchar(50),
	`author` varchar(50),
	`price`	decimal(11,2),
	`sales`	int,
	`stock` int
);

## 插入初始化测试数据
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` ) 
values(null , '3天精通java' , '菜丸' , 55 ,555 , 5);

insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` ) 
values(null , 'JVM底层原理' , '菜丸' , 66 , 666 , 6);

insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` ) 
values(null , '数据结构' , '菜丸' , 77, 777 , 7);

select * from t_user;
select * from t_book;

逆向工程配置文件

<?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="DB2Tables" targetRuntime="MyBatis3">

        <!-- 去掉全部的注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- 修改 数据库的 连接属性 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mbg"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--配置生成javaBean的
                targetPackage javaBean的包名
                targetProject 生成在哪个项目目录下
        -->
        <javaModelGenerator targetPackage="com.caiwan.pojo" targetProject=".\mybatis-mbg\src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--
                   配置生成的Mapper.xml配置文件
                                targetPackage javaBean的包名
                                targetProject 生成在哪个项目目录下
        -->
        <sqlMapGenerator targetPackage="com.caiwan.mapper"  targetProject=".\mybatis-mbg\src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 配置生成Mapper接口 -->
      <javaClientGenerator type="XMLMAPPER" targetPackage="com.caiwan.mapper"
                             targetProject=".\mybatis-mbg\src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!--
            数据库一个表对应一个table标签
                tableName是表名
                domainObjectName 设置生成的类名
        -->
        <table tableName="t_user" domainObjectName="User" />
        <table tableName="t_book" domainObjectName="Book" />
    </context>
</generatorConfiguration>

执行逆向工程的代码:

package com.caiwan.mbg.runner;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MbgRunner {

    public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mybatis-mbg/mbg.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);
    }
}

生成测试代码:

package com.caiwan.test;
import com.caiwan.mapper.BookMapper;
import com.caiwan.pojo.Book;
import com.caiwan.pojo.BookExample;
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.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

public class BookMapperTest {
    static SqlSessionFactory sqlSessionFactory;

	// @BeforeClass在当前类的所有测试方法之前执行。注解在【静态方法】上。
    @BeforeClass
    public static void init() throws IOException {
        sqlSessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
    }


    @Test
    public void countByExample() {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            BookMapper mapper = session.getMapper(BookMapper.class);
            // 创建一个条件类
            BookExample bookExample = new BookExample();
            // 创建一个查询条件
            BookExample.Criteria criteria = bookExample.createCriteria();

//            where xxx = xxx and xxx = xxx;
//            where xxx = xxx or xxx = xxx;

            // 查询价格大于16的图书有几条记录
//            criteria.andPriceGreaterThan(new BigDecimal(16));
            // 查询销量大于10 , 且 库存 大于50的记录
//            criteria.andSalesGreaterThan(10);
//            criteria.andStockGreaterThan(50);

            // 查询销量大于10 , 或 库存 大于50的记录
            criteria.andSalesEqualTo(10);
            bookExample.or().andStockGreaterThan(50);

            // count() 用于查询数量的方法
            // count 用于查询数量的
            // ByExample按条件来查询
            int i = mapper.countByExample(bookExample);
            System.out.println(i);
        } finally {
            session.close();
        }
    }

    @Test
    public void deleteByExample() {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            BookMapper mapper = session.getMapper(BookMapper.class);
//            mapper.deleteByExample(null);// 只要条件是空,就是全表操作
            BookExample bookExample = new BookExample();
            bookExample.createCriteria().andSalesGreaterThan(10000);

            mapper.deleteByExample(bookExample);

            session.commit();
        } finally {
            session.close();
        }

    }

    @Test
    public void deleteByPrimaryKey() {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            BookMapper mapper = session.getMapper(BookMapper.class);

            mapper.deleteByPrimaryKey(8);

            session.commit();
        } finally {
            session.close();
        }

    }

    @Test
    public void insert() {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            BookMapper mapper = session.getMapper(BookMapper.class);

            mapper.insert(new Book(null,"刷leetcode的一百道题", "菜丸1", new BigDecimal(1234), 1234,1234));
            mapper.insert(new Book(null,"java从入门到放弃", "菜丸2", new BigDecimal(1234), 1234,1234));

            session.commit();

        } finally {
            session.close();
        }

    }

    @Test
    public void insertSelective() {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            BookMapper mapper = session.getMapper(BookMapper.class);

            Book book = new Book(null,"数据库", null,null,100,100);

            // 方法末尾Selective就表示操作的时候,不带null值的列
//            mapper.insertSelective(book);// null列不在操作范围内
            mapper.insert(book);// null列一样在操作范围内

            session.commit();
        } finally {
            session.close();
        }
    }

    @Test
    public void selectByExample() {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            BookMapper mapper = session.getMapper(BookMapper.class);
            BookExample bookExample = new BookExample();
            bookExample.createCriteria().andIdBetween(1,10);
            // 设置排序字段
            bookExample.setOrderByClause(" price desc ");
//            List books = mapper.selectByExample(null);// 条件为null,就整表操作
            List<Book> books = mapper.selectByExample(bookExample);// 有条件
            books.forEach(System.out::println);
        } finally {
            session.close();
        }
    }

    @Test
    public void selectByPrimaryKey() {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            BookMapper mapper = session.getMapper(BookMapper.class);
            Book book = mapper.selectByPrimaryKey(6);
            System.out.println(book);

        } finally {
            session.close();
        }
    }

    @Test
    public void updateByExampleSelective() {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            BookMapper mapper = session.getMapper(BookMapper.class);

            Book book = new Book(null,"忽略null的列", null, null,1234,124);
            BookExample bookExample = new BookExample();
            bookExample.createCriteria().andIdGreaterThan(8);
            /**
             * 根据条件来进行更新,而且不带null的列
             */
            mapper.updateByExampleSelective(book,bookExample);
            session.commit();
        } finally {
            session.close();
        }
    }

    @Test
    public void updateByExample() {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            BookMapper mapper = session.getMapper(BookMapper.class);

            Book book = new Book(null,"忽略null的列", null, null,1234,124);
            BookExample bookExample = new BookExample();
            bookExample.createCriteria().andIdGreaterThan(8);
            /**
             * 根据条件来进行更新,而且不带null的列
             */
            mapper.updateByExample(book,bookExample);

            session.commit();

        } finally {
            session.close();
        }
    }

    @Test
    public void updateByPrimaryKeySelective() {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            BookMapper mapper = session.getMapper(BookMapper.class);

            Book book = new Book(null,"忽略null的列", null, null,1234,124);

            /**
             * 根据条件来进行更新,而且不带null的列
             */
            mapper.updateByPrimaryKeySelective(book);
            session.commit();

        } finally {
            session.close();
        }
    }

    @Test
    public void updateByPrimaryKey() {

        SqlSession session = sqlSessionFactory.openSession();

        try {
            BookMapper mapper = session.getMapper(BookMapper.class);
            Book book = new Book(null,"忽略null的列", null, null,1234,124);

            /**
             * 根据条件来进行更新
             */
            mapper.updateByPrimaryKey(book);
            session.commit();

        } finally {
            session.close();
        }
    }
}

文章持续更新:欢迎各位小伙伴关注我的公众号:菜丸的程序屋。希望将我的不足之处给予指点,谢谢大家。喜欢Java,热衷学习的小伙伴可以加我微信: CaiWan_Y
逆向工程_第1张图片
逆向工程_第2张图片

你可能感兴趣的:(mybatis,数据库,mybatis,java,sql)