SpringBoot+Mybatis+MySql 自动生成代码 自动分页

SpringBoot+Mybatis+MySql 自动生成代码 自动分页

一、配置文件

<!-- 通用mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.1.5</version>
        </dependency>
        <!-- pagehelper 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
<!-- 自动生成代码 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.34</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>3.4.4</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <phase>package</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <!--允许移动生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 是否覆盖 -->
                    <overwrite>true</overwrite>
                    <!-- 自动生成的配置 -->
                    <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
                </configuration>
            </plugin>
spring:
  profiles:
    active: dev

logging:
  config: classpath:xml/logback-boot.xml

mybatis:
  # type-aliases扫描路径
  type-aliases-package: com.czhappy.wanmathapi.entity
  # mapper xml实现扫描路径
  mapper-locations: classpath:mapper/*.xml
  property:
    order: BEFORE

#mappers 多个接口时逗号隔开
mapper:
  mappers: com.czhappy.wanmathapi.config.MyMapper
  not-empty: false
  identity: mysql

#pagehelper分页配置 第二种和第三种不需要 重点讲的第一种需要
pagehelper:
  helperDialect: mysql
  reasonable: false
  supportMethodsArguments: true
  params: count=countSql

 

二、Dao配置

自定义MyMapper,作为dao的父类,此文件不要和其他dao文件放一起,防止扫描时有影响,单独建个文件夹。

package com.czhappy.wanmathapi.config;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {

}

三、service配置

package com.czhappy.wanmathapi.service;

import org.springframework.stereotype.Service;

import java.util.List;

@Service
public interface IService<T> {

    List<T> selectAll();

    T selectByKey(Object key);

    int save(T entity);

    int delete(Object key);

    int updateAll(T entity);

    int updateNotNull(T entity);

    List<T> selectByExample(Object example);
}
package com.czhappy.wanmathapi.service.impl;

import com.czhappy.wanmathapi.service.IService;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

public abstract class BaseService<T> implements IService<T> {

    @Autowired
    protected Mapper<T> mapper;

    public Mapper<T> getMapper() {
        return mapper;
    }

    @Override
    public List<T> selectAll() {
        //说明:查询所有数据
        return mapper.selectAll();
    }

    @Override
    public T selectByKey(Object key) {
        //说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
        return mapper.selectByPrimaryKey(key);
    }

    @Override
    public int save(T entity) {
        //说明:保存一个实体,null的属性也会保存,不会使用数据库默认值
        return mapper.insert(entity);
    }

    @Override
    public int delete(Object key) {
        //说明:根据主键字段进行删除,方法参数必须包含完整的主键属性
        return mapper.deleteByPrimaryKey(key);
    }

    @Override
    public int updateAll(T entity) {
        //说明:根据主键更新实体全部字段,null值会被更新
        return mapper.updateByPrimaryKey(entity);
    }

    @Override
    public int updateNotNull(T entity) {
        //根据主键更新属性不为null的值
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public List<T> selectByExample(Object example) {
        //说明:根据Example条件进行查询
        //重点:这个查询支持通过Example类指定查询列,通过selectProperties方法指定查询列
        return mapper.selectByExample(example);
    }
}

四、自动生成代码mybatis-generator.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="mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">

        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.czhappy.wanmathapi.config.MyMapper"/>
            <!--caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true-->
            <property name="caseSensitive" value="false"/>
        </plugin>

        <!-- 阻止生成自动注释 -->
        <commentGenerator>
            <property name="javaFileEncoding" value="UTF-8"/>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/wanmath"
                        userId="root" password="root">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="com.czhappy.wanmathapi.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--生成Dao类存放位置-->
        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.czhappy.wanmathapi.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--生成对应表及类名去掉Mybatis Generator生成的一堆 example-->
        <table tableName="sys_dict" domainObjectName="SysDict" enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="mysql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

五、目录结构

双击生成实体类、mapper、dao相关代码:

posted @ 2019-06-04 10:31 chenzheng8975 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,需要在pom.xml中引入相应的依赖,这里以MySQL数据库为例: ```xml <!-- SpringBoot Web模块 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- SpringBoot Mybatis模块 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MySQL驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> ``` 其次,需要配置Mybatis和数据库连接,可以在application.yml中配置: ```yml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC&useSSL=false&characterEncoding=utf8 username: root password: root mybatis: config-location: classpath:mybatis-config.xml mapper-locations: classpath:mapper/*.xml ``` 其中,`datasource`为数据源的基本信息,`mybatis`则是Mybatis的配置信息,包括配置文件的位置和Mapper文件的位置。 接下来,需要编写Mapper接口和对应的Mapper XML文件。以User表为例: ```java public interface UserMapper { List<User> findUserByPage(@Param("start") Integer start, @Param("pageSize") Integer pageSize); } ``` ```xml <mapper namespace="com.example.demo.mapper.UserMapper"> <select id="findUserByPage" resultType="com.example.demo.entity.User"> select * from user limit #{start},#{pageSize} </select> </mapper> ``` 其中,`findUserByPage`方法为分页查询方法,`start`为起始位置,`pageSize`为每页数量。 最后,编写Controller层和前端页面。以UserController为例: ```java @Controller public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/user") public String findUserByPage(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, Model model) { Integer start = (pageNum - 1) * pageSize; List<User> userList = userMapper.findUserByPage(start, pageSize); PageInfo pageInfo = new PageInfo(userList); model.addAttribute("pageInfo", pageInfo); return "user"; } } ``` 其中,`findUserByPage`方法接收两个参数:`pageNum`和`pageSize`,表示当前页和每页数量。通过计算获得起始位置,调用Mapper接口进行分页查询,并通过`PageInfo`类将查询结果传递给前端页面。 在前端页面中通过`th:each`循环遍历查询结果,并通过`th:href`生成分页链接。以user.html为例: ```html <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>User List</title> </head> <body> <table border="1"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Gender</th> </tr> </thead> <tbody> <tr th:each="user : ${pageInfo.list}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> <td th:text="${user.gender}"></td> </tr> </tbody> </table> <div> <a th:href="@{/user?pageNum=1}">首页</a> <a th:href="@{/user?pageNum=${pageInfo.prePage}}">上一页</a> <a th:href="@{/user?pageNum=${pageInfo.nextPage}}">下一页</a> <a th:href="@{/user?pageNum=${pageInfo.pages}}">尾页</a> </div> </body> </html> ``` 其中,`pageInfo.list`为查询结果列表,通过`th:each`循环遍历生成表格数据。底部的分页链接则通过`th:href`生成相应的链接。 到这里,一个简单的分页查询就完成了。需要注意的是,以上代码仅为示例,具体实现方式可能会有所不同,需要按照实际需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值