MyBatis的逆向工程



  • 正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。Hibernate是支持正向工程的
  • 逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:
  • Java实体类
    • Mapper接口
    • Mapper映射文件

创建逆向工程的步骤

添加依赖和插件

<dependencies>
    <!-- MyBatis核心依赖包 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
    </dependency>
    <!-- junit测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.27</version>
    </dependency>
    <!-- log4j日志 -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!-- log4j日志 -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>
<!-- 控制Maven在构建过程中相关配置 -->
<build>
    <!-- 构建过程中用到的插件 -->
    <plugins>
        <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.0</version>
            <!-- 插件的依赖 -->
            <dependencies>
                <!-- 逆向工程的核心依赖 -->
                <dependency>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-core</artifactId>
                    <version>1.3.2</version>
                </dependency>
                <!-- 数据库连接池 -->
                <dependency>
                    <groupId>com.mchange</groupId>
                    <artifactId>c3p0</artifactId>
                    <version>0.9.2</version>
                </dependency>
                <!-- MySQL驱动 -->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.27</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

创建MyBatis的核心配置文件

mybatis-config

<?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>

    <properties resource="jdbc.properties"></properties>

    <typeAliases>
        <package name="com.study.mybatis.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.study.mybatis.mapper"/>
    </mappers>
</configuration>

创建逆向工程的配置文件

  • 文件名必须是: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>
    <!--
    targetRuntime: 执行生成的逆向工程的版本
    MyBatis3Simple: 生成基本的CRUD(清新简洁版)
    MyBatis3: 生成带条件的CRUD(奢华尊享版)
    -->
    <context id="DB2Tables" targetRuntime="MyBatis3Simple">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- javaBean的生成策略-->
        <!--生成到 targetProject 下的 targetPackage目录下-->
        <javaModelGenerator targetPackage="com.study.mybatis.pojo" targetProject=".\src\main\java">
            <!--开启使用子包,如果不开启targetPackage属性就会为包的名字-->
            <property name="enableSubPackages" value="true" />
            <!--去掉字段前后的空格-->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- SQL映射文件的生成策略 -->
        <!--SQL映射文件在 targetProject下的targetPackage目录下-->
        <sqlMapGenerator targetPackage="com.study.mybatis.mapper"
                         targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- Mapper接口的生成策略 -->
        <!--注意:这里的targetPackage属性要与SQL映射文件生成策略要相同-->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.study.mybatis.mapper" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 逆向分析的表 -->
        <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
        <!-- domainObjectName属性指定生成出来的实体类的类名 -->
        <!--
            tableName:为表名
            domainObjectName:为实体类的名
        -->
        <table tableName="t_emp" domainObjectName="Emp"/>
        <table tableName="t_dept" domainObjectName="Dept"/>
    </context>
</generatorConfiguration>

执行MBG插件的generate目标

在这里插入图片描述
在这里插入图片描述
执行结果
目录都会自动生成,mapper中有基本的增删改查功能
在这里插入图片描述

QBC

generatorConfig.xml

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

MyBatis3自动生成的方法

注意事项:

  1. 带Example 都是根据条件进行操作
  2. 带Selective 都是选择性进行操作
  3. 选择性插入与其他插入的区别在于
    • 其他插入如果插入值为null,那么会将字段的值设置为null
    • 选择性插入如果插入值为null,那么就不会为字段的值赋值
  4. 选择性更新和其他更新的区别
    • 其他更新如果更新值为null,那么会将字段的值设置为null
    • 选择性更新更新如果更新值为null,那么就不会为字段的值赋值


EmpExample example: 条件对象
Integer eid:对应主键
Emp record:对应实体类对象

方法作用
------------------------计数------------------------------------------------------------------------------
int countByExample(EmpExample example);根据条件计数
------------------------删除------------------------------------------------------------------------------
int deleteByExample(EmpExample example);根据条件删除
int deleteByPrimaryKey(Integer eid);根据主键删除
------------------------插入------------------------------------------------------------------------------
int insert(Emp record);插入
int insertSelective(Emp record);选择性插入
------------------------查询------------------------------------------------------------------------------
List<Emp> selectByExample(EmpExample example);根据条件查询
Emp selectByPrimaryKey(Integer eid);根据主键查询
------------------------更新------------------------------------------------------------------------------
int updateByExampleSelective(
@Param(“record”) Emp record,
@Param(“example”) EmpExample example);
选择性根据条件更新
int updateByExample(
@Param(“record”) Emp record,
@Param(“example”) EmpExample example);
根据条件更新
int updateByPrimaryKeySelective(Emp record);选择性根据主键更新
int updateByPrimaryKey(Emp record);根据主键更新

使用流程:同样是通过mapper接口的.class对象得到实现类,然后调用相应的方法
在这里插入图片描述

使用条件进行操作

  1. 使用实体类对应的example对象的createCriteria()方法创建条件
  2. 属性条件姓名规律:and+属性名+判断操作
    • 如: andEmpNameEqualTo(“张三”): 查找EmpName属性值为张三的数据
    • 多个条件为可以往后连接,都为and关系
  3. 如果多个条件为 or 关系,那么使用example.or()后面跟条件即可
//创建example对象
EmpExample example = new EmpExample();
//判断条件为:empName为"张三"并且eid为空 或者 age大于20的数据
example.createCriteria().andEmpNameEqualTo("张三").andEidIsNotNull();
example.or().andAgeGreaterThan(20);
//查找此条件的数据
List<Emp> emps = mapper.selectByExample(example);

在这里插入图片描述

根据条件查询

@Test
public void testMBG() throws IOException {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);

    //创建example对象
    EmpExample example = new EmpExample();
    /*
        1、使用example对象的createCriteria()方法创建条件
        2、属性条件姓名规律:and+属性名+判断操作
          - 如: andEmpNameEqualTo("张三"): 查找EmpName属性值为张三的数据
          - 多个条件为可以往后连接,都为and关系
        3、如果多个条件为 or 关系,那么使用example.or()后面跟条件即可
     */
    example.createCriteria().andEmpNameEqualTo("张三").andEidIsNotNull();
    example.or().andAgeGreaterThan(20);
    List<Emp> emps = mapper.selectByExample(example);
    emps.forEach(emp -> System.out.println(emp));
}

DEBUG 04-29 18:25:43,188 ==> Preparing: select eid, emp_name, age, sex, email, did from t_emp WHERE ( emp_name = ? and eid is not null ) or( age > ? ) (BaseJdbcLogger.java:137)

查询所有

//查询所有员工
List<Emp> emps1 = mapper.selectByExample(null);
emps1.forEach(emp -> System.out.println(emp));

选择性修改与其他修改

在这里插入图片描述

//用选择性修改 主键为1的用户
int rows = mapper.updateByPrimaryKeySelective(new Emp(1, "老七", null, null, null, null));
System.out.println("改变的行数: " + rows);

可以发现更新的值为null的字段并不会写入到数据库中
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值