MyBatis逆向工程详细教程

1 导入逆向工程到eclipse中

2 修改配置文件

注意修改以下几点:

  1. 修改要生成的数据库表
  2. pojo文件所在包路径
  3. Mapper所在的包路径

配置文件如下:

<?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://39.105.94.154:3306/mybatis"
            userId="tom"
            password="tom,">
        </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="com.mybatis.spring.pojo"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.mybatis.spring.mapper"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.mybatis.spring.mapper"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table schema="" tableName="user"></table>
        <table schema="" tableName="orders"></table>

        <!-- 有些表的字段需要指定java类型
             比如我们表里面有一个字段是tinyint类型,范围-128~127.
             你会发现它自己生成的时候会生成一个Boolean类型。
             他认为之后装0,和 1.
             如果说你想装0,1,2,3,4,5,6多个值,这时候boolean就不行了。
             这时候你就需要指定一下tinyint类型的字段转换后的类型为int。
         <table schema="" tableName="">
            <columnOverride column="id" javaType="int" />
        </table> -->
    </context>
</generatorConfiguration>

3 生成逆向工程代码

找到下图所示的java文件,执行工程main主函数,

刷新工程,发现代码生成,如下图:

4 测试逆向工程代码

1 新建一个java工程名为mybatis-spring-second

2.复制刚刚生成的逆向工程代码到项目中,效果如下

修改spring配置文件

在applicationContext.xml修改.注意使用扫描的方式配置代理

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                           http://www.springframework.org/schema/util
                           http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 1加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 2配置连接池 -->
    <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!--3 配置SqlSessionFactory  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置mybatis核心配置文件 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- Mapper代理的方式开发,扫描包方式配置代理 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置Mapper接口,如果需要加载多个包,直接写进来,中间用,分隔 -->
        <property name="basePackage" value="com.mybatis.spring.mapper"></property>
    </bean>

</beans>

修改SqlMapConfig.xml文件

<?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>
    <!-- 设置别名 -->
    <typeAliases>
        <!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
        <package name="com.mybatis.spring.pojo" />
    </typeAliases>

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

注意事项

注意:

  1. 逆向工程生成的代码只能做单表查询
  2. 不能在生成的代码上进行扩展,因为如果数据库变更,需要重新使用逆向工程生成代码,原来编写的代码就被覆盖了。
  3. 一张表会生成4个文件

测试程序

package com.mybatis.spring.junit;

import java.util.Date;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mybatis.spring.mapper.UserMapper;
import com.mybatis.spring.pojo.User;
import com.mybatis.spring.pojo.UserExample;

public class UserMapperTest {

    private ApplicationContext ac;

    @Before
    public void setUp() throws Exception {
        this.ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }

    @Test
    //测试插入,插入全部字段
    public void testInsert() {
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        User user = new User();
        user.setUsername("曹操");
        user.setSex("1");
        user.setBirthday(new Date());
        user.setAddress("三国");

        userMapper.insert(user);
    }

    @Test
    //测试插入,插入部分字段全部字段
    public void testInsertSelective() {
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        User user = new User();
        user.setUsername("卢小西");

        user.setBirthday(new Date());

        userMapper.insertSelective(user);
    }

    @Test
    //测试根据条件删除
    public void testDeleteByExample(){
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        // 创建User对象扩展类,用户设置查询条件
        UserExample example = new UserExample();
        example.createCriteria().andUsernameLike("%西%");

        //删除数据
        int deleteCount = userMapper.deleteByExample(example);

        System.out.println("删除了:"+deleteCount+"条数据");

    }

    @Test
    //测试根据id删除
    public void testDeleteByPrimaryKey(){
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        //删除数据
        int deleteCount = userMapper.deleteByPrimaryKey(38);

        System.out.println("删除了:"+deleteCount+"条数据");

    }

    @Test
    //查询名字里面含有张的用户
    public void testSelectByExample1() {
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        // 创建User对象扩展类,用户设置查询条件
        UserExample example = new UserExample();
        example.createCriteria().andUsernameLike("%张%");

        // 查询数据
        List<User> list = userMapper.selectByExample(example);

        System.out.println(list.size());
    }

    @Test
    //查询性别为1,并且名字里面含有“明”字的,并且降序排序
    public void testSelectByExample2() {
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        // 创建User对象扩展类,用户设置查询条件
        UserExample example = new UserExample();
        String username = "明";
        example.createCriteria().andSexEqualTo("1").andUsernameLike("%" + username + "%");
        example.setOrderByClause("id desc");

        List<User> list = userMapper.selectByExample(example);
        for (User u : list) {
            System.out.println(u.getId() + "\t" + u.getUsername());
        }
    }

    @Test
    //查询性别为1,并且名字里面含有“明”字的用户数量
    public void testSelectByExample3() {
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        // 创建User对象扩展类,用户设置查询条件
        UserExample example = new UserExample();
        String username = "明";
        example.createCriteria().andSexEqualTo("1").andUsernameLike("%" + username + "%");

        int count = userMapper.countByExample(example);
        System.out.println(count);
    }

    @Test
    public void testSelectByPrimaryKey() {
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        User user = userMapper.selectByPrimaryKey(31);
        System.out.println(user.getId()+"\t"+user.getUsername()+"\t"+
        user.getAddress()+"\t"+user.getSex()+"\t"+user.getBirthday());
    }

    @Test
    //测试用户修改,根据id,修改全部字段
    public void testUpdateByPrimaryKey(){
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        User user = new User();
        user.setId(1);
        user.setUsername("曹操");
        user.setSex("1");
        user.setBirthday(new Date());
        user.setAddress("三国");

        userMapper.updateByPrimaryKey(user);
        System.out.println(user);
    }

    @Test
    //测试用户修改,根据id,但是只修改其中的某个字段,或者某几个字段,非全部字段
    public void testUpdateByPrimaryKeySelective(){
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        User user = new User();
        user.setId(1);
        user.setUsername("诸葛亮");

        userMapper.updateByPrimaryKeySelective(user);
        System.out.println(user.getId()+"\t"+user.getUsername());
    }

    @Test
    //测试用户修改,根据example,修改全部字段
    public void testUpdateByExample(){
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        //创建需要修改的用户对象
        User user = new User();
        user.setId(1);
        user.setUsername("习大大");
        user.setSex("1");
        user.setBirthday(new Date());
        user.setAddress("china");

        // 创建User对象扩展类,用户设置查询条件
        UserExample example = new UserExample();
        example.createCriteria().andIdEqualTo(1);

        userMapper.updateByExample(user, example);

        System.out.println(user.getId()+"\t"+user.getUsername());
    }

    @Test
    //测试用户修改,根据id,但是只修改其中的某个字段,或者某几个字段,非全部字段
    public void testUpdateByExampleSelective(){
        // 获取Mapper
        UserMapper userMapper = ac.getBean(UserMapper.class);

        //创建需要修改的用户对象
        User user = new User();
        user.setId(1);
        user.setUsername("小强");
        user.setSex("2");

        // 创建User对象扩展类,用户设置查询条件
        UserExample example = new UserExample();
        example.createCriteria().andIdEqualTo(1);

        userMapper.updateByExampleSelective(user, example);

        System.out.println(user.getId()+"\t"+user.getUsername());
    }
}

原文地址:https://www.cnblogs.com/jepson6669/p/9029888.html

时间: 2024-08-13 23:12:30

MyBatis逆向工程详细教程的相关文章

SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)

使用SSM(Spring.SpringMVC和Mybatis)已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方.之前没有记录SSM整合的过程,这次刚刚好基于自己的一个小项目重新搭建了一次,而且比项目搭建的要更好一些.以前解决问题的过程和方法并没有及时记录,以后在自己的小项目中遇到我再整理分享一下.这次,先说说三大框架整合过程.个人认为使用框架并不是很难,关键要理解其思想,这对于我们提高编程水平很有帮助.不过,如果用都不会,谈思想就

Maven+MySQL+Spring+SpringMVC+Mybatis(详细)

本来想写一个大而全的详细教程的,包括一些使用技巧,后来发现自己有点Hold不住的感觉(不信你试试),就改写一个扫盲篇了 整篇博文包括maven安装,mysql安装,环境搭建,以及配置扫盲.框架的搭建会从裸Mybatis来开始,到整合Spring,再到前台显示(SpringMVC). 首先来看maven的安装. 这个很简单,在官网上下载apache-maven-3.*.*-bin.zip或者apache-maven-3.*.*-bin.tar.gz(注意标识-bin) 博主这里下载的是apache

回顾一下MyBatis逆向工程——自动生成代码

前言 最近做的项目(SSM+Shiro)的数据库表已经创建完成,一共有15张表,如果我们一个个去写pojo/bean的代码以及各种sql语句的话未免太过麻烦而且很容易出错,这个时候我们就需要MyBatis逆向工程去为我们生成这些基本的东西.先来简单的了解一下什么是逆向工程 一 什么是逆向工程 官网解释浓缩版:MyBatis逆向工程需要用到的就是MyBatis官方提供的MyBatis Generator(MBG).MBG是MyBatis和iBATIS的代码生成器,它将为所有版本的MyBatis以及

安装python3的详细教程

安装python3的详细教程 环境:CentOS 7 1. 安装依赖环境 # yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel 2. 浏览器打开 https://www.python.org/ftp/python/ 查看最新的Python版本,标记为3.A

linux安装 Android Studio详细教程

安装 Android Studio详细教程 libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1 jdk1.8.0_25 android-studio-ide-141.2456560-linux.zip android-sdk_r24.4.1-linux.tgz  Android SDK中的adb程序是32位的,Ubuntu x64系统需要安装32位库文件,用于兼容32位的程序.如果不安装,adb会出错:java.io.IOExcepti

Xcode和github入门详细教程

Xcode和github详细教程! 主要是参考了现在网上的一些资料给没整过的人一个详细的指南. (1)先在github上注册账号,自行解决! (2)在导航栏右上角new一个repository(仓库). (3)填写仓库的名称.描述等信息.第二部是设置公开或者私人项目,隐私项目适合于公司的代码托管但是是收费的. (4)下面就不用管了,在MAC电脑上生成你的ssh秘钥,此处转载http://www.cnblogs.com/sorex/archive/2012/05/25/2517763.html.

MyEclipse 2014 破解图文详细教程

MyEclipse 2014 破解图文详细教程 原文地址:http://blog.my-eclipse.cn/myeclipse-2014-crack.html MyEclipse2014 Windows版下载地址:http://pan.baidu.com/s/10VoL4 MyEclipse作为Java EE最受欢迎的IDE,如今最新版本为2014版,今天给大家带来MyEclipse 2014破解的方法. 一.安装完成MyEclipse2014(适用于2013等版本)后,不要打开软件,下载破解

SQL Server 数据导入Mysql详细教程

SQL Server 数据导入Mysql详细教程 SQL Server数据库和Mysql 数据库都是关系型数据库,虽然很多数据库都对SQL语句进行了再开发和扩展,使得在不同的数据库中执行的方法或用法不一,但是 SQL Server,Mysql ,Access等都采用了SQL语言标准,不同的数据库中的数据是可以导入的.对于大数据的导入是有相当大的意义. 今天,我和大家一起分享一下,我用的便捷的"sql server 数据导入mysql 中的方法",希望能给大家的项目开发中"sq

server-U_汉化版详细教程

启动Serv-U adminisrator之后,出现如图界面,先看看"本地服务器"这个项目,如图,有个选项是"自动开始(系统服务)",选中后,Serv-U就把自己注册成系统服务,开机自动运行,而且在用户没有登录的情况下就开始运行了. 这里说说Serv-U的运行方式,看看安装后的根目录,有几个文件:ServUAdmin.exe是配置管理工具,ServUTray.exe是驻留系统托盘的工具,ServUDaemon.exe是Serv-U后台运行的守护程序.只要ServUD