Mybatis自动生成Mapper、xml文件以及Example的使用

对于常用的基本的数据库操纵和数据查询,无需再手动去编写sql,使用程序生成,开发效率更高,当然要会用啦!

主要有两种方法:

1、使用java命令生成;

2、使用java程序生成 

下面介绍第一种方法:

使用java命令生成Mapper.java、xml文件

1、编写Mybatis生成文件的配置文件

<?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 location="C:\\Users\\11985\\.m2\\repository\\mysql\\mysql-connector-java\\8.0.19\\mysql-connector-java-8.0.19.jar" />
    <context id="myContext" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true" />
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库链接地址账号密码 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/mybatis_test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=false"
                        userId="root" password="root">
            <!--使用Connector / J的8.x版,需要加这个属性,否则会生成xxxKey,xxxWithBlobs等文件-->
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!--生成实体类类存放位置 -->
        <javaModelGenerator targetPackage="com.boot.mybatis.po"
            targetProject="src/main/java/">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!--生成映射文件存放位置 -->
        <sqlMapGenerator targetPackage="mapper"
            targetProject="src/main/resources/">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!--生成Dao类存放位置 -->
        <javaClientGenerator type="XMLMAPPER" 
            targetPackage="com.boot.mybatis.dao" targetProject="src/main/java/">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!--生成对应表及类名-->
		<table tableName="user" domainObjectName="User"></table>
    </context>
</generatorConfiguration>

 2、输入如下指令(参考:MyBatis Generator Quick Start Guide

java -jar mybatis-generator-core-x.x.x.jar -configfile generatorConfig.xml -overwrite

我测试成功的例子是:

java -jar C:\Users\11985\.m2\repository\org\mybatis\generator\mybatis-generator-core\1.3.5\mybatis-generator-core-1.3.5.jar -configfile D:\java\idea-work
space\mybatis\src\main\resources\generatorConfig.xml -overwrite

使用命令的好处:

mybatis-generator-core-x.x.x.jar包和generatorConfig.xml可以不在项目中,和项目分离单独使用。这样可以避免项目后期开发中的意外导致重要文件被覆盖!

 

使用java程序生成Mapper.java、xml文件

1、添加依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.19</version>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.5</version>
</dependency>

2、使用MyBatisGenerator生成文件

public class MyBatisGeneratorTest {

    public static void main(String[] args) {
        try {
            List<String> warnings = new ArrayList<>();

            File configFile = new File("D:\\java\\idea-workspace\\mybatis\\src\\main\\resources\\generatorConfig.xml");

            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(configFile);
            DefaultShellCallback callback = new DefaultShellCallback(true);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

下面是由java程序生成的文件的使用(Example)

Mapper.java文件源码如下:

public interface UserMapper {
    
    /**
     * 根据example查询符合条件的记录数
     */
    long countByExample(UserExample example);

    /**
     * 根据example删除符合条件的记录
     */
    int deleteByExample(UserExample example);

    /**
     * 根据主键删除记录
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * 插入
     */
    int insert(User record);

    /**
     * 选择性插入
     */
    int insertSelective(User record);

    /**
     * 根据example查询符合条件的记录
     */
    List<User> selectByExample(UserExample example);

    /**
     * 根据主键查询记录
     */
    User selectByPrimaryKey(Integer id);

    /**
     * 根据example选择性更新记录
     */
    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);

    /**
     * 根据example更新记录
     */
    int updateByExample(@Param("record") User record, @Param("example") UserExample example);

    /**
     * 根据主键选择性更新记录
     */
    int updateByPrimaryKeySelective(User record);

    /**
     * 根据主键更新记录
     */
    int updateByPrimaryKey(User record);
}

关于选择性的意思,我在下面的测试类中的注释有介绍。

测试类如下:

import com.boot.mybatis.po.User;
import com.boot.mybatis.po.UserExample;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @author river
 * 2020/2/10
 */
@SpringBootTest
class UserMapperTest {

    @Resource
    UserMapper userMapper;

    @Test
    void countByExample() {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserNameLike("river%");
        long count = userMapper.countByExample(userExample);
        assertNotEquals(count, 0);
    }

    @Test
    void deleteByExample() {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserNameEqualTo("river4");
        int influenceLine = userMapper.deleteByExample(userExample);
        assertNotEquals(influenceLine, 0);
    }

    @Test
    void deleteByPrimaryKey() {
        int influenceLineNum = userMapper.deleteByPrimaryKey(4);
        assertNotEquals(influenceLineNum, 0);
    }

    @Test
    void insert() {
        User user = new User();
        user.setUserName("river6");
        user.setPassword("121212");
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int influenceLineNum = userMapper.insert(user);//不能为null的值,必须设置值,数据库默认值不起作用
        assertNotEquals(influenceLineNum, 0);
    }

    @Test
    void insertSelective() {
        User user = new User();
        user.setUserName("river66");
        user.setPassword("123123");
        int influenceLineNum = userMapper.insertSelective(user);//为null值的字段,数据库会该字段设为默认值
        assertNotEquals(influenceLineNum, 0);
    }

    @Test
    void selectByExample() {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserNameLike("river%");
        List<User> users = userMapper.selectByExample(userExample);
        assertNotEquals(users.size(),0);
    }

    @Test
    void selectByPrimaryKey() {
        User user = userMapper.selectByPrimaryKey(1);
        assertEquals(user.getId(),1);
    }

    @Test
    void updateByExampleSelective() {
        User user = new User();
        user.setPassword("666");
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserNameEqualTo("river66");
        int influenceLineNum = userMapper.updateByExampleSelective(user, userExample);//选择性更新,将river66的记录对应的password更新为666
        assertNotEquals(influenceLineNum, 0);
    }

    @Test
    void updateByExample() {
        User user = userMapper.selectByPrimaryKey(1);
        user.setPassword("666666");
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andIdEqualTo(user.getId());
        int influenceLineNum = userMapper.updateByExample(user, userExample);//user中的所有信息所有更新到数据库,包括值为null的字段
        assertNotEquals(influenceLineNum, 0);
    }

    @Test
    void updateByPrimaryKeySelective() {
        User user = new User();
        user.setId(1);
        user.setPassword("168168");
        int influenceLineNum = userMapper.updateByPrimaryKeySelective(user);//根据主键选择性更新,null值字段不会更新到数据库
        assertNotEquals(influenceLineNum, 0);
    }

    @Test
    void updateByPrimaryKey() {
        User user = userMapper.selectByPrimaryKey(1);
        user.setPassword("168666");
        int influenceLineNum = userMapper.updateByPrimaryKey(user);//根据主键选择性更新,null值字段不会更新到数据库
        assertNotEquals(influenceLineNum, 0);
    }
}

最后附上数据库sql和application.yml文件,以及github地址:https://github.com/bigBigRiver/MybatisGenerator.git

/*
Navicat MySQL Data Transfer

Source Server         : superMeSql
Source Server Version : 80019
Source Host           : localhost:3306
Source Database       : mybatis_test

Target Server Type    : MYSQL
Target Server Version : 80019
File Encoding         : 65001

Date: 2020-02-10 20:13:49
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'river', '666666', '2020-01-21 12:33:20', '2020-02-10 18:34:04');
INSERT INTO `user` VALUES ('2', 'river1', '123456', '2020-01-21 12:35:49', '2020-01-21 12:35:49');
INSERT INTO `user` VALUES ('3', 'river2', '123456', '2020-01-21 12:36:22', '2020-01-21 12:36:22');
INSERT INTO `user` VALUES ('6', 'river66', '666', '2020-02-10 18:06:32', '2020-02-10 18:32:18');
INSERT INTO `user` VALUES ('7', 'river6', '121212', '2020-02-10 18:09:15', '2020-02-10 18:09:15');
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis_test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.boot.mybatis.po

 

发布了86 篇原创文章 · 获赞 144 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章