mybatis-逆向工程

环境


mybatis-generator-core-1.4.0.jar:https://github.com/mybatis/generator/releases
文档:http://mybatis.org/generator/

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 80022
 Source Host           : localhost:3306
 Source Schema         : school

 Target Server Type    : MySQL
 Target Server Version : 80022
 File Encoding         : 65001

 Date: 20/11/2021 17:20:00
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for teacher
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `tea_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `tea_age` int(0) NULL DEFAULT NULL,
  `tea_email` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 65 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of teacher
-- ----------------------------
INSERT INTO `teacher` VALUES (1, 'set', 22, 'tom@qq.com');
INSERT INTO `teacher` VALUES (2, 'lili', 22, 'lili@qq.com');
INSERT INTO `teacher` VALUES (3, 'lucy', 22, 'lucy@qq.com');
INSERT INTO `teacher` VALUES (4, 'lisi', 22, 'lisi@qq.com');
INSERT INTO `teacher` VALUES (62, 'teacher1', 22, '1@qq.com');
INSERT INTO `teacher` VALUES (63, 'teacher2', 22, '2@qq.com');
INSERT INTO `teacher` VALUES (64, 'teacher3', 22, '3@qq.com');

SET FOREIGN_KEY_CHECKS = 1;
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
db.username=root
db.password=123456
#dbconfig.properties
# Global logging configuration
log4j.rootLogger=debug, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
#log4j.properties
<?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="dbconfig.properties"/>
    
    <settings>
        <!--开启驼峰命名自动映射-->
        <!--mybatis-config.xml-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="lazyLoadingEnabled" value="trie"/>
        <!--mybatis-config.xml-->
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.fly.entity"/>
    </typeAliases>

    <environments default="development">
        <!--每个environment是一个环境,default属性指向使用哪个环境-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--mybatis-config.xml-->
    <databaseIdProvider type="DB_VENDOR">
        <property name="MySQL" value="mysql"/>
        <property name="Oracle" value="oracle"/>
    </databaseIdProvider>
    
    <mappers>
        <mapper resource="mapper/TeacherMapper.xml"/>
    </mappers>

</configuration>



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

    <!--mgb.xml-->
    
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/school?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT%2B8&amp;allowPublicKeyRetrieval=true"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <!--
            The <javaTypeResolver> element is used to define properties of the Java Type Resolver.
            The Java Type Resolver is used to calculate Java types from database column information.
            The default Java Type Resolver attempts to make JDBC DECIMAL and NUMERIC types easier to use by substituting Integral types if possible (Long, Integer, Short, etc.) If this behavior is undesirable, set the property "forceBigDecimals" to "true".
            You can also substitute your own implementation if you want different behavior than the default.
            This element is an optional child element of the <context> element.
            Note: if you use the MyBatis3Kotlin runtime,
            then the generator will automatically convert Java types to their appropriate Kotlin equivalents when applicable.
        -->
        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--
            The <javaModelGenerator> element is used to define properties of the Java model generator.
            The Java Model Generator builds primary key classes,
            record classes, and Query by Example classes that match the introspected table.
            This element is a required child element of the <context> element.
            javaModelGenerator:指定javaBean的生成策略
            targetPackage="test.model":目标包名
	        targetProject="\MBGTestProject\src":目标工程
        -->
        <javaModelGenerator targetPackage="com.fly.entity" targetProject=".\src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--
            The <sqlMapGenerator> element is used to define properties of the SQL map generator.
            The SQL Map Generator builds a MyBatis formatted SQL map XML file for each introspected table.
            This element is a required child element of the <context> element only if your chosen javaClientGenerator requires XML.
            The runtimes based on MyBatis Dynamic SQL do not generate XML and will ignore this element if it is specified.
            sql映射生成策略
        -->
        <sqlMapGenerator targetPackage="mapper"  targetProject=".\config">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!--
            javaClientGenerator:指定mapper接口所在的位置
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.fly.mapper"  targetProject=".\src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 指定要逆向分析哪些表:根据表要创建javaBean -->
        <table tableName="teacher" domainObjectName="Teacher"/>
    </context>
</generatorConfiguration>

测试

简单查询

  @Test
  public void test() throws InterruptedException, SQLException, IOException, InvalidConfigurationException, XMLParserException {
    List<String> warnings = new ArrayList<>();
    boolean overwrite = true;
    File configFile = new File("mgb.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);
  }



  @Test
  public void test1() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
      TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
      Teacher teacher = mapper.selectByPrimaryKey(1);
      System.out.println("teacher = " + teacher);
    }
  }

模糊查询

  @Test
  public void test2() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
      TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
      TeacherExample example = new TeacherExample();
      TeacherExample.Criteria criteria = example.createCriteria();
      criteria.andTeaNameLike("%l%");
      List<Teacher> teachers = mapper.selectByExample(example);
      for (Teacher teacher : teachers) {
        System.out.println(teacher.getTeaName());
      }
    }
  }

两个条件

  @Test
  public void test3() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
      TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
      TeacherExample example = new TeacherExample();
      TeacherExample.Criteria criteria = example.createCriteria();
      criteria.andTeaNameLike("%l%");
      TeacherExample.Criteria criteria1 = example.createCriteria();
      criteria1.andTeaEmailLike("%1%");
      example.or(criteria1);
      List<Teacher> teachers = mapper.selectByExample(example);
      for (Teacher teacher : teachers) {
        System.out.println(teacher.getTeaName() + "\t" + teacher.getTeaEmail());
      }
    }
  }

posted @ 2021-11-20 20:17  翻蹄亮掌一皮鞋  阅读(49)  评论(0)    收藏  举报