首页 > 其他分享 >spring和Mybatis的逆向工程

spring和Mybatis的逆向工程

时间:2024-06-12 19:55:18浏览次数:9  
标签:empId 逆向 spring System println Emp Mybatis null out

目录

十二、注解开发

注解方式比较简单,但是实际开发不推荐使用注解,使用配置文件的方式,不需要改源代码)

1、注解方式单表的增删改查的操作

(1)查询所有

/**
 * 查询所有
 * @return
 */
@Select("select * from user")
List<User> findAll();
@Test
public void testFindAll(){
    List<User> users = userMapper.findAll();
    users.forEach(System.out::println);
}

(2)根据id查询

/**
 * 通过id查询用户
 * @param id
 * @return
 */
@Select("select * from user where id=#{id}")
User findUserById(Integer id);
@Test
public void testFindUserById(){
    User user = userMapper.findUserById(2);
    System.out.println(user);
}

十三、逆向工程

正向工程:先创建java实体类,有框架负责根据实体类生成数据库表。Hibernate是支持正向工程

逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:

⑴Java实体类

⑵Mapper接口

⑶Mapper映射文件

注意:逆向工程生成的都是单表资源

13.1、创建逆向工程的步骤

⑴添加依赖

<!-- 控制Maven在构建过程中相关配置 -->
<build>
    <!-- 构建过程中用到的插件 -->
    <plugins>
        <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.0</version>
            <!-- 插件的依赖 -->
            <dependencies>
                <!-- 逆向工程的核心依赖 -->
                <dependency>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-core</artifactId>
                    <version>1.3.2</version>
                </dependency>
                <!-- MySQL驱动 -->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.1.6</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
 	

⑵配置MyBatis的核心配置文件

配置pojo包和mapper包

⑶创建逆向工程的配置文件,该文件文件名必须是: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>
    <!--
    targetRuntime: 执行生成的逆向工程的版本
    MyBatis3Simple: 生成基本的CRUD(清新简洁版)
    MyBatis3: 生成带条件的CRUD(奢华尊享版)
    -->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis_demo"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <!-- javaBean的生成策略-->
        <javaModelGenerator targetPackage="com.qcby.mybatis.pojo"
                            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- SQL映射文件的生成策略 -->
        <sqlMapGenerator targetPackage="com.qcby.mybatis.mapper"
                         targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- Mapper接口的生成策略 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.qcby.mybatis.mapper" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 逆向分析的表 -->
        <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
        <!-- domainObjectName属性指定生成出来的实体类的类名 -->
        <table tableName="emp" domainObjectName="Emp"/>
        <table tableName="dept" domainObjectName="Dept"/>
    </context>
</generatorConfiguration>

13.2测试

/**
 * 根据主键查询
 */
@Test
public void testSelectByPrimaryKey(){

    Emp emp = empMapper.selectByPrimaryKey(1);
    System.out.println(emp);
}

/**
 * 带条件查询
 */
@Test
public void testSelectByExample(){
    List<Emp> emps = empMapper.selectByExample(null);
    emps.forEach(System.out::println);
}

@Test
public void testSelectByExample2(){
    EmpExample example = new EmpExample();
    example.createCriteria().andEmpNameEqualTo("李四").andAgeGreaterThanOrEqualTo(22);

    List<Emp> emps = empMapper.selectByExample(example);
    emps.forEach(System.out::println);
}

@Test
public void testSelectByExample3(){
    EmpExample example = new EmpExample();
    example.createCriteria().andEmpNameEqualTo("王五").andAgeGreaterThanOrEqualTo(22);
    example.or().andSexEqualTo("男");

    List<Emp> emps = empMapper.selectByExample(example);
    emps.forEach(System.out::println);
}

@Test
public void testUpdateByPrimaryKey(){
    Emp emp = new Emp(2,"小张",null,"女");
    // int i  = empMapper.updateByPrimaryKey(emp);
    // if(i>0){
    //     System.out.println("更新成功");
    // }else {
    //     System.out.println("更新失败");
    // }

    int i = empMapper.updateByPrimaryKeySelective(emp);
    if(i>0){
        System.out.println("更新成功");
    }else {
        System.out.println("更新失败");
    }
}

十四、分页插件

14.1、使用步骤

⑴添加依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.0</version>
</dependency>

⑵配置分页插件

在MyBatis的核心配置文件中配置插件

<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

14.2分页插件的使用

PageInfo{pageNum=1, pageSize=5, size=5, startRow=1, endRow=5, total=42, pages=9, list=Page{count=true, pageNum=1, pageSize=5, startRow=0, endRow=5, total=42, pages=9, reasonable=false, pageSizeZero=false}[Emp{empId=1, empName='小张', age=null, sex='女'}, Emp{empId=2, empName='小张', age=22, sex='女'}, Emp{empId=3, empName='王五', age=24, sex='男'}, Emp{empId=4, empName='马六', age=25, sex='女'}, Emp{empId=5, empName='赵七', age=26, sex='男'}], prePage=0, nextPage=2, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, navigatePages=5, navigateFirstPage=1, navigateLastPage=5, navigatepageNums=[1, 2, 3, 4, 5]}
Page{count=true, pageNum=2, pageSize=5, startRow=5, endRow=10, total=42, pages=9, reasonable=false, pageSizeZero=false}[Emp{empId=8, empName='a', age=null, sex='null'}, Emp{empId=13, empName='a', age=null, sex='null'}, Emp{empId=14, empName='a', age=null, sex='null'}, Emp{empId=20, empName='a', age=null, sex='null'}, Emp{empId=22, empName='a', age=null, sex='null'}]
a>在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能 
pageNum:当前页的页码 
pageSize:每页显示的条数 
b>在查询获取list集合之后,使用PageInfo<T> pageInfo = new PageInfo<>(List<T> list, int 
navigatePages)获取分页相关数据 
list:分页之后的数据 
navigatePages:导航分页的页码数 
c>分页相关数据 
PageInfo{ 
pageNum=8, pageSize=4, size=2, startRow=29, endRow=30, total=30, pages=8, 
list=Page{count=true, pageNum=8, pageSize=4, startRow=28, endRow=32, total=30, 
pages=8, reasonable=false, pageSizeZero=false}, 
prePage=7, nextPage=0, isFirstPage=false, isLastPage=true, hasPreviousPage=true, 
hasNextPage=false, navigatePages=5, navigateFirstPage4, navigateLastPage8, 
navigatepageNums=[4, 5, 6, 7, 8] 
} 
pageNum:当前页的页码 
pageSize:每页显示的条数 
size:当前页显示的真实条数 
total:总记录数 
pages:总页数 
prePage:上一页的页码 
nextPage:下一页的页码 
isFirstPage/isLastPage:是否为第一页/最后一页 
hasPreviousPage/hasNextPage:是否存在上一页/下一页 
navigatePages:导航分页的页码数 
navigatepageNums:导航分页的页码,[1,2,3,4,5] 

标签:empId,逆向,spring,System,println,Emp,Mybatis,null,out
From: https://www.cnblogs.com/ning23/p/18244601

相关文章

  • springboot rabbitmq如何保证消息顺序消费
    很多时候,消息的消费是不用保证顺序的,比如借助mq实现订单超时的处理。但有些时候,业务中可能会存在多个消息需要顺序处理的情况,比如生成订单和扣减库存消息,那肯定是先执行生成订单的操作,再执行扣减库存的操作。那么这种情况下,是如何保证消息顺序消费的呢?首先,为了效率,我们可以设置......
  • 【第三篇】SpringSecurity请求流程分析
    简介本篇文章主要分析一下SpringSecurity在系统启动的时候做了那些事情、第一次请求执行的流程是什么、以及SpringSecurity的认证流程是怎么样的,主要的过滤器有哪些?SpringSecurity初始化流程1.加载配置文件web.xml当Web服务启动的时候,会加载我们配置的web.xml文件web.xml......
  • DockerCompose+Jenkins+Pipeline流水线打包SpringBoot项目(解压安装配置JDK、Maven等)
    场景DockerCompose中部署Jenkins(DockerDesktop在windows上数据卷映射):https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/139491855Docker+Jenkins+Gitee+Maven项目配置jdk、maven、gitee等拉取代码并自动构建以及遇到的那些坑:https://blog.csdn.net/BADAO_LIUMANG_......
  • springboot集成socketio
    1.引入依赖<dependency><groupId>com.corundumstudio.socketio</groupId><artifactId>netty-socketio</artifactId><version>2.0.3</version></dependency>2.基本配置server:port:8081socketio:host:localho......
  • SpringCloudNetflix组件整合
    SpringCloudNetflix组件整合Eureka注册中心Eureka是什么Eureka是netflix的一个子模块,也是核心模块之一,Eureka是一个基于REST的服务,用于定位服务,以实现云端中间层服务发现和故障转移。服务注册与发现对于微服务架构来说是非常重要的,有了服务发现和注册,只需要使用服务的标......
  • springboot3项目的搭建四.3(security登录认证配置)
    security的jwt验证:总体来说,我们加入依赖项,security就已经开始生效了,但是使用的默认的UserDetails和UserDetailsService,一、我们只要继承UserDetailsService,在数据库中查询用户和权限列表,封装成UserDetails的实现类,返回就可以实现,security验证的接管,最多在security配置类中,放行......
  • SpringBoot 多文件打包下载
    第一种@RestController@RequestMapping("/download")publicclassDownloadController{@GetMapping("/files")publicResponseEntity<InputStreamResource>downloadFiles()throwsIOException{//......
  • Mybatis快速入门
    文章目录1.Mybatis概述1.1Mybatis概念1.2JDBC缺点1.3Mybatis优化2.Mybatis快速入门3.Mapper代理开发3.1Mapper代理开发概述3.2使用Mapper代理要求3.3案例4.核心配置文件4.1多环境配置4.2类型别名1.Mybatis概述1.1Mybatis概念MyBatis是一款......
  • mybatis的mapper中的sql涉及嵌套且外部引用导致的问题:XML fragments parsed from prev
    假设xxx.xml中有类似下方的sql嵌套:<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.xx......
  • MybatisPlus - [04] 分页查询
    limitm,n、PageHelper、MyBatisPlus分页插件 一、拦截器分页(1)在MybatisPlusConfig中进行配置@BeanpublicMybatisPlusInterceptorpaginationInterceptor(){MybatisPlusInterceptorinterceptor=newMybatisPlusInterceptor();interceptor.addInnerIntercep......