首页 > 代码库 > Mybatis逆向工程——(一)

Mybatis逆向工程——(一)

  逆向工程可以快速将数据库的表生成JavaBean,同时生成对单标操作的Mapper.java与Mapper.xml,极大地提高了开发速度。

1.jar包

  技术分享

2.配置文件

  需要修改数据库连接信息,mapper生成目录与pojo生成位置,也要修改要导出的表。

  工程目录下配置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>    <context id="testTables" targetRuntime="MyBatis3">        <commentGenerator>            <!-- 是否去除自动生成的注释 true:是 : false:否 -->            <property name="suppressAllComments" value="true" />        </commentGenerator>        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->        <jdbcConnection driverClass="com.mysql.jdbc.Driver"            connectionURL="jdbc:mysql://localhost:3306/exam" userId="root"            password="123456">        </jdbcConnection>        <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"            connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"             userId="yycg"            password="yycg">        </jdbcConnection> -->        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和             NUMERIC 类型解析为java.math.BigDecimal -->        <javaTypeResolver>            <property name="forceBigDecimals" value="false" />        </javaTypeResolver>        <!-- targetProject:生成PO类的位置 -->        <javaModelGenerator targetPackage="cn.xm.pojo"            targetProject=".\src">            <!-- enableSubPackages:是否让schema作为包的后缀 -->            <property name="enableSubPackages" value="false" />            <!-- 从数据库返回的值被清理前后的空格 -->            <property name="trimStrings" value="true" />        </javaModelGenerator>        <!-- targetProject:mapper映射文件生成的位置 -->        <sqlMapGenerator targetPackage="cn.xm.mapper"             targetProject=".\src">            <!-- enableSubPackages:是否让schema作为包的后缀 -->            <property name="enableSubPackages" value="false" />        </sqlMapGenerator>        <!-- targetPackage:mapper接口生成的位置 -->        <javaClientGenerator type="XMLMAPPER"            targetPackage="cn.xm.mapper"             targetProject=".\src">            <!-- enableSubPackages:是否让schema作为包的后缀 -->            <property name="enableSubPackages" value="false" />        </javaClientGenerator>        <!-- 指定数据库表 -->        <table tableName="blacklist"></table>            <table tableName="breakrules"></table>            <table tableName="checkrecord"></table>            <table tableName="department"></table>            <table tableName="dictionary"></table>            <table tableName="employee_in"></table>            <table tableName="employee_out"></table>            <table tableName="employeeexam"></table>            <table tableName="exam"></table>            <table tableName="exampaper"></table>            <table tableName="historypaperoption"></table>            <table tableName="historypaperquestion"></table>            <table tableName="newsrecord"></table>            <table tableName="onlineexamanswerinfor"></table>            <table tableName="onlineexaminfor"></table>            <table tableName="options"></table>            <table tableName="permission"></table>            <table tableName="pictureindex"></table>            <table tableName="project"></table>            <table tableName="questionbank"></table>            <table tableName="questions"></table>            <table tableName="role"></table>            <table tableName="rolepermission"></table>            <table tableName="traincontent"></table>            <table tableName="unit"></table>            <table tableName="unitproject"></table>            <table tableName="userrole"></table>        </context></generatorConfiguration>

 

3.  Java程序

 1 package mybatisInverse; 2 import java.io.File; 3 import java.util.ArrayList; 4 import java.util.List; 5 import org.mybatis.generator.api.MyBatisGenerator; 6 import org.mybatis.generator.config.Configuration; 7 import org.mybatis.generator.config.xml.ConfigurationParser; 8 import org.mybatis.generator.internal.DefaultShellCallback; 9 10 public class GeneratorSqlmap11 {12   public void generator()13     throws Exception14   {15     List<String> warnings = new ArrayList();16     boolean overwrite = true;17     18     File configFile = new File("generatorConfig.xml");19     ConfigurationParser cp = new ConfigurationParser(warnings);20     Configuration config = cp.parseConfiguration(configFile);21     DefaultShellCallback callback = new DefaultShellCallback(overwrite);22     MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, 23       callback, warnings);24     myBatisGenerator.generate(null);25   }26   27   public static void main(String[] args)28     throws Exception29   {30     try31     {32       GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();33       generatorSqlmap.generator();34     }35     catch (Exception e)36     {37       e.printStackTrace();38     }39   }40 }

 

运行结果:

技术分享

 

4.使用生成的代码:

  对单表操作较方便,可以自定义条件查询。

 

 

sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 加载属性文件 -->    <properties resource="db.properties">        <!--properties中还可以配置一些属性名和属性值  -->        <!-- <property name="jdbc.driver" value=""/> -->    </properties>    <!-- 全局配置参数,需要时再设置 -->    <!-- <settings>        </settings> -->        <!-- 别名定义 -->    <typeAliases>                <!-- 针对单个别名定义        type:类型的路径        alias:别名         -->        <!-- <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/> -->        <!-- 批量别名定义         指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以)        -->        <package name="cn.xm.pojo"/>            </typeAliases>        <!-- 和spring整合后 environments配置将废除-->    <environments default="development">        <environment id="development">        <!-- 使用jdbc事务管理,事务控制由mybatis-->            <transactionManager type="JDBC" />        <!-- 数据库连接池,由mybatis管理-->            <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>        <!--通过resource方法一次加载一个映射文件 -->        <!-- <mapper resource="mapper/UserMapper.xml"/> -->                <!-- 通过mapper接口加载单个 映射文件        遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中        上边规范的前提是:使用的是mapper代理方法         -->        <!-- <mapper class="cn.itcast.mybatis.mapper.UserMapper"/> -->                <!-- 批量加载mapper        指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载        遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中        上边规范的前提是:使用的是mapper代理方法         -->        <package name="cn.xm.mapper"/>    </mappers>    </configuration>

 

 

java代码:

package cn.xm.test;import java.io.InputStream;import java.net.URL;import java.util.Date;import java.util.List;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.apache.tomcat.jdbc.pool.interceptor.SlowQueryReportJmxMBean;import org.junit.Before;import org.junit.Test;import cn.xm.mapper.EmployeeInMapper;import cn.xm.pojo.EmployeeIn;import cn.xm.pojo.EmployeeInExample;public class MybatisTest {    private SqlSessionFactory sqlSessionFactory;    @Before    public void setUp() throws Exception {        // 将全局配置文件作为一个流        String resource = "sqlMapConfig.xml";        URL realPath2 = Resources.getResourceURL("sqlMapConfig.xml");        InputStream inputStream = Resources.getResourceAsStream(resource);        // 建立一个SqlSession工厂        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);    }    // 测试增加    @Test    public void testAdd() throws Exception {        SqlSession sqlSession = sqlSessionFactory.openSession();        EmployeeInMapper eim = sqlSession.getMapper(EmployeeInMapper.class);        EmployeeIn sl = new EmployeeIn();        sl.setIdcode("33");        sl.setEmployeeid("3");        sl.setEmployeenumber("3");        sl.setPassword("33333");        ;        sl.setName("王五");        eim.insert(sl);        sqlSession.commit();        sqlSession.close();    }    // 测试删除    @Test    public void testDeleteById() throws Exception {        SqlSession sqlSession = sqlSessionFactory.openSession();        EmployeeInMapper eim = sqlSession.getMapper(EmployeeInMapper.class);        eim.deleteByPrimaryKey("3");        sqlSession.commit();        sqlSession.close();    }    // 测试修改    @Test    public void fun2() throws Exception {        SqlSession sqlSession = sqlSessionFactory.openSession();        EmployeeInMapper eim = sqlSession.getMapper(EmployeeInMapper.class);        EmployeeIn selectByPrimaryKey = eim.selectByPrimaryKey("3");        selectByPrimaryKey.setName("这是修改后的值");        eim.updateByPrimaryKey(selectByPrimaryKey);        sqlSession.commit();        sqlSession.close();    }    // 测试通过id查询单个    @Test    public void fun3() throws Exception {        SqlSession sqlSession = sqlSessionFactory.openSession();        EmployeeInMapper eim = sqlSession.getMapper(EmployeeInMapper.class);        EmployeeIn selectByPrimaryKey = eim.selectByPrimaryKey("3");        System.out.println(selectByPrimaryKey);    }    // 自定义条件查询 查询名字为张三的    @Test    public void testSelectByExample() {        SqlSession sqlSession = sqlSessionFactory.openSession();        EmployeeInMapper eim = sqlSession.getMapper(EmployeeInMapper.class);        EmployeeInExample employeeInExample = new EmployeeInExample();        // 通过criteria构造查询条件        EmployeeInExample.Criteria criteria = employeeInExample.createCriteria();        criteria.andNameEqualTo("张三");        // 可能返回多条记录        List<EmployeeIn> list = eim.selectByExample(employeeInExample);        System.out.println(list);    }    // 自定义条件查询 查询名字为张三的且password为44444的    @Test    public void testSelectByExample1() {        SqlSession sqlSession = sqlSessionFactory.openSession();        EmployeeInMapper eim = sqlSession.getMapper(EmployeeInMapper.class);        EmployeeInExample employeeInExample = new EmployeeInExample();        // 通过criteria构造查询条件        EmployeeInExample.Criteria criteria = employeeInExample.createCriteria();        criteria.andNameEqualTo("张三");        criteria.andPasswordEqualTo("44444");        // 可能返回多条记录        List<EmployeeIn> list = eim.selectByExample(employeeInExample);        System.out.println(list);    }    // 自定义条件查询 查询所有,只是不封装条件    @Test    public void testSelectByExample3() {        SqlSession sqlSession = sqlSessionFactory.openSession();        EmployeeInMapper eim = sqlSession.getMapper(EmployeeInMapper.class);        EmployeeInExample employeeInExample = new EmployeeInExample();        // 通过criteria构造查询条件        EmployeeInExample.Criteria criteria = employeeInExample.createCriteria();        // 可能返回多条记录        List<EmployeeIn> list = eim.selectByExample(employeeInExample);        System.out.println(list);    }}

 

Mybatis逆向工程——(一)