• Mybatis上路_06-使用Java自动生成


    1.编写Generator执行配置文件:

                generatorConfigation.xml。注意配置数据库驱动包的绝对路径。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    <?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:/mysql-connector-java-5.1.22-bin.jar" />
      
        <!-- 环境配置 **************************************************
            id="自定义的配置名称"
            targetRuntime="MyBatis版本" -->
        <context id="MySqlTables" targetRuntime="MyBatis3" >
        
            <!-- 数据库  ===============================================
                driverClass="驱动"
                connectionURL="数据库url"
                userId="用户"
                password="密码" -->
            <jdbcConnection
                driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://127.0.0.1:3306/db_mybatis" 
                userId="root"
                password="root">  
            </jdbcConnection>
     
            <!-- Java数据类型分离器,数据类型转换 =====================
                property 属性
                    name="强迫双精度"
                    value="不" -->
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false" />
            </javaTypeResolver>
      
            <!-- Java模型生成器 =======================================
                targetPackage="生成文件的目标路径"
                targetProject="已存在的项目包"
                    enableSubPackages-可以省略对应约束名,true-是的,可以省略tb_generator
                    trimString-验证字符串,true-是的 -->
            <javaModelGenerator
                    targetPackage="cn.cvu.test.model"
                    targetProject="src">
                <property name="enableSubPackages" value="false" />
                <property name="trimStrings" value="true" />
            </javaModelGenerator>
      
            <!-- sql映射文件生成器 =======================================
                targetPackage="生成文件的目标路径"
                targetProject="已存在的项目包"
                    enableSubPackages-可以省略对应约束名,true-是的,可以省略tb_generator -->
            <sqlMapGenerator
                    targetPackage="cn.cvu.test.xml"
                    targetProject="src">
                <property name="enableSubPackages" value="false" />
            </sqlMapGenerator>
      
            <!-- java委托对象DAO生成器,接口 =============================
                type=""
                targetPackage="生成文件的目标路径"
                targetProject="已存在的项目包"
                    enableSubPackages-可以省略对应约束名,true-是的,可以省略tb_generator -->
            <javaClientGenerator
                    type="XMLMAPPER"
                    targetPackage="cn.cvu.test.dao"
                    targetProject="src">
                <property name="enableSubPackages" value="false" />
            </javaClientGenerator>
            
            <!-- 表单,已存在,根据此表生成其它文件 =======================
                tableName="已有的表单名称"
                domainObjetctName="对应生成的文件名前缀" -->
            <table tableName="tb_generator" domainObjectName="Eminem">
                <!-- useActualColumnNames-使用真实列名 ,
                     true-嗯。如果false,则由columnOverride节点控制  -->
                <property name="useActualColumnNames" value="true" />
                
                <!-- 标识列
                    column="列名" sqlStatement="某种数据库语言" identity="作为主键" -->
                <generatedKey column="id" sqlStatement="MySql" identity="true" />
                
                <!-- 覆盖项,当property name="useActualColumnNames" value="true"时。
                    column="被覆盖值的列名" property="用来覆盖的对应的java类的属性" -->
                <columnOverride column="name" property="generName" />
      
            </table>
            
        </context>
     
    </generatorConfiguration>

    2.在MyEclipse中建空web项目:

                将配置文件放到src里。加入generator的jar文件。

                

    3.编写并执行Java程序:

                

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    package cn.cvu.test.build;
      
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    import org.junit.Test;
    import org.mybatis.generator.api.MyBatisGenerator;
    import org.mybatis.generator.config.Configuration;
    import org.mybatis.generator.config.xml.ConfigurationParser;
    import org.mybatis.generator.internal.DefaultShellCallback;
      
    public class TestGenerateWithJava {
      
        @Test
        public void testBuild() throws Exception {
                    // 信息缓存
                    List<String> warnings = new ArrayList<String>();
                    // 覆盖已有的重名文件
                    boolean overwrite = true;
                    // 准备 配置文件
                    File configFile = new File("F:/myeclipse_workspace/generator/src/generatorConfigation.xml");
                    // 1.创建 配置解析器
                    ConfigurationParser parser = new ConfigurationParser(warnings);
                    // 2.获取 配置信息
                    Configuration config = parser.parseConfiguration(configFile);
                    // 3.创建 默认命令解释调回器
                    DefaultShellCallback callback = new DefaultShellCallback(overwrite);
                    // 4.创建 mybatis的生成器
                    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
                    // 5.执行,关闭生成器
            myBatisGenerator.generate(null);
        }
    }

    4.查看并修改生成的文件:

                选中src,按F5刷新,可以看到新文件已经创建:

                

                修改报错的EmineMapper.java文件,去除注解:

                



    5.测试,使用生成的文件查询:

    1)导入MyBatis的jar包:

                    mybatis-3.2.2.jar 
                    mybatis-generator-core-1.3.2.jar 
                    mysql-connector-java-5.1.22-bin.jar 

    2)创建MyBatis的xml配置文件:

                    上面我们注释掉了自动生成的注解代码,在src新建一个xml配置文件,mybatisConfigation.xml:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <?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>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC" />
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://127.0.0.1:3306/db_mybatis" />
                    <property name="username" value="root" />
                    <property name="password" value="root" />
                </dataSource>
            </environment>
        </environments>
     
        <mappers>
            <!-- 引入MBG生成器创建的映射文件 -->
            <mapper resource="cn/cvu/test/xml/EminemMapper.xml" />
        </mappers>
    </configuration>

    3)Java测试代码:

                    创建测试类cn.cvu.test.dotest.TestDoGeneratorWithJava :

                    

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    package cn.cvu.test.dotest;
     
    import java.io.Reader;
    import java.util.List;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    import cn.cvu.test.dao.EminemMapper;
    import cn.cvu.test.model.Eminem;
    import cn.cvu.test.model.EminemExample;
    import cn.cvu.test.model.EminemExample.Criteria;
     
    public class TestDoGeneratorWithJava {
     
        @Test
        public void testQuery() throws Exception {
     
            // 创建SQL会话:
            Reader reader = Resources.getResourceAsReader("mybatisConfigation.xml");
            SqlSession session = new SqlSessionFactoryBuilder().build(reader).openSession();
     
            // 创建查询实例:
            EminemExample eminemExample = new EminemExample();
     
            // 获取映射实体:
            EminemMapper mapper = session.getMapper(EminemMapper.class);
     
            // 利用实体通过实例查询全部条目
            List<Eminem> eminems = mapper.selectByExample(eminemExample);
            System.out.println("ID name notes ");
            for (Eminem eminem : eminems) {
                    System.out.println(eminem.getId()+
                                    " "+eminem.getGenerName()+
                                    " "+eminem.getNotes());
            }
            session.close();
        }
    }
     

    - end 
  • 相关阅读:
    课后作业成绩汇总
    关于作业提交要求声明 2017-09-22
    团队编程项目作业成绩汇总
    结对项目作业成绩汇总
    团队组信息
    小知识记录:第XI篇
    小知识记录:第X篇
    小知识记录:第十二篇
    小知识记录:第十一篇
    小知识记录:第十篇
  • 原文地址:https://www.cnblogs.com/a757956132/p/4380103.html
Copyright © 2020-2023  润新知