spring boot+mybatis+mysql增删改查分页
server:
port:
servlet:
context-path: /springBootMybatis spring:
datasource:
name: test
url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&useSSL=true
username: root
password: root
#新版数据库驱动使用com.mysql.cj.jdbc.Driver 旧版com.mysql.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource mybatis:
#这里是实体类的位置,#实体扫描,多个package用逗号或者分号分隔
#typeAliasesPackage: com.hegg.springboot.model
type-aliases-package: com.hegg.springboot.model
#把xml文件放在com.XX.mapper.*中可能会出现找不到的问题,这里把他放在resource下的mapper中
mapper-locations: classpath:mapper/*.xml #分页插件
pagehelper:
helperDialect: mysql #分页插件方言选择
reasonable: true #合理化参数,设为true时pageNum<=0 时会查第一页, pageNum>pages(超过总数时),会查询最后一页
supportMethodsArguments: true
1、先附上application.yml的配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hegg</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>Demo project for Spring Boot</description> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<scope>runtime</scope>-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<!--<scope>test</scope>-->
</dependency> <!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency> <!-- mybatis的分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin> <!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build> </project>
2、pom.xml的代码,其中三段代码是自己加的
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency> <!-- mybatis的分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin> 3、新建generatorConfig.xml用来自动生成实体类和对应的*Mapper.xml和*Mapper.java(*Mapper.java是接口interface)
<?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="E:\apache-maven\repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<!--新版数据库驱动com.mysql.cj.jdbc.Driver 旧版com.mysql.jdbc.Driver-->
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&useSSL=true"
userId="root"
password="root">
</jdbcConnection> <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver> <!-- 生成模型的包名和位置-->
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径
-->
<javaModelGenerator targetPackage="com.hegg.springboot.model" targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<property name="trimStrings" value="true"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator> <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator> <!-- 生成DAO的包名和位置-->
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.hegg.springboot.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
4、编译运行生成代码点击run>Edit Configuration,如下图找到maven在标注的位置输入对应的代码运行即可generator和
mybatis-generator:generate -e。千万不要重复运行,不然在*Mapper.xml中就会重复生成方法,还有
generatorConfig.xml文件中连接数据使用的jar包不要使用太高的版本。
5、下面是生成的接口代码UserMapper.java,其中后面三个方法是自己加的,其他的都是自动生成的,
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.hegg.springboot.model.User; import java.util.List; public interface UserMapper {
int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); List<User> getAllUser(); Page<User> findByPage(); PageInfo<User> findByPageInfo();
}
UserMapper.xml中后面三个方法是自己加的
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hegg.springboot.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.hegg.springboot.model.User" >
<constructor >
<idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="name" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="sex" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="age" jdbcType="INTEGER" javaType="java.lang.Integer" />
</constructor>
</resultMap>
<sql id="Base_Column_List" >
id, name, sex, age
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.hegg.springboot.model.User" >
insert into user (id, name, sex,
age)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=INTEGER},
#{age,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.hegg.springboot.model.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="name != null" >
name,
</if>
<if test="sex != null" >
sex,
</if>
<if test="age != null" >
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="sex != null" >
#{sex,jdbcType=INTEGER},
</if>
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.hegg.springboot.model.User" >
update user
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null" >
sex = #{sex,jdbcType=INTEGER},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.hegg.springboot.model.User" >
update user
set name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=INTEGER},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update> <select id="getAllUser" resultType="com.hegg.springboot.model.User" parameterType="java.util.List">
select
<include refid="Base_Column_List"/>
from USER
</select>
<select id="findByPage" resultType="com.hegg.springboot.model.User" parameterType="com.github.pagehelper.Page">
select
<include refid="Base_Column_List"/>
from USER
</select>
<select id="findByPageInfo" resultType="com.hegg.springboot.model.User" parameterType="com.github.pagehelper.PageInfo">
select
<include refid="Base_Column_List"/>
from USER
</select>
</mapper>
贴出UserService.java、UserServiceImpl.java、UserController.java的代码
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.hegg.springboot.model.User; import java.util.List; public interface UserService {
int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); List<User> getAllUser(); Page<User> findByPage(Integer pageNum, Integer pageSize); PageInfo<User> findByPageInfo(Integer pageNum, Integer pageSize); }
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hegg.springboot.mapper.UserMapper;
import com.hegg.springboot.model.User;
import com.hegg.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class UserServiceImpl implements UserService { @Autowired
private UserMapper userMapper;//这个里会报红,但不影响 @Override
public int deleteByPrimaryKey(Integer id) {
return userMapper.deleteByPrimaryKey(id);
} @Override
public int insert(User record) {
return userMapper.insert(record);
} @Override
public int insertSelective(User record) {
return userMapper.insertSelective(record);
} @Override
public User selectByPrimaryKey(Integer id) {
return userMapper.selectByPrimaryKey(id);
} @Override
public int updateByPrimaryKeySelective(User record) {
return userMapper.updateByPrimaryKeySelective(record);
} @Override
public int updateByPrimaryKey(User record) {
return userMapper.updateByPrimaryKey(record);
} @Override
public List<User> getAllUser() {
return userMapper.getAllUser();
} @Override
public Page<User> findByPage(Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
return userMapper.findByPage();
} @Override
public PageInfo<User> findByPageInfo(Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userMapper.findByPage();
PageInfo<User> pageInfo = new PageInfo<>(userList);
return pageInfo;
} }
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.hegg.springboot.common.MyResponse;
import com.hegg.springboot.model.User;
import com.hegg.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import java.util.List; @RestController
@RequestMapping("/userController")
public class UserController { @Autowired
private UserService userService; @RequestMapping(value = "/hello", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
@ResponseBody
public String getHello() {
return "Hello,Word!!!世界5";
} @RequestMapping(value = "/selectByPrimaryKey", method = RequestMethod.POST)
@ResponseBody
public MyResponse selectByPrimaryKey(Integer id){
User user = this.userService.selectByPrimaryKey(id);
MyResponse response = new MyResponse();
if(null != user){
response.setCode("success");
response.setMsg("成功");
response.setData(user);
} else {
response.setCode("faild");
response.setMsg("失败");
}
return response;
} @RequestMapping(value = "/getAllUser", method = RequestMethod.POST)
@ResponseBody
public MyResponse getAllUser(){
List<User> list = this.userService.getAllUser();
MyResponse response = new MyResponse();
if(null != list && list.size() > 0){
response.setCode("success");
response.setMsg("成功");
response.setData(list);
} else {
response.setCode("faild");
response.setMsg("失败");
}
return response;
} @RequestMapping(value = "/findByPage", method = RequestMethod.POST)
@ResponseBody
public MyResponse findByPage(Integer pageNum, Integer pageSize){
Page<User> list = this.userService.findByPage(pageNum, pageSize);
MyResponse response = new MyResponse();
if(null != list && list.size() > 0){
response.setCode("success");
response.setMsg("成功");
response.setData(list);
} else {
response.setCode("faild");
response.setMsg("失败");
}
return response;
} @RequestMapping(value = "/findByPageInfo", method = RequestMethod.POST)
@ResponseBody
public MyResponse findByPageInfo(Integer pageNum, Integer pageSize){
PageInfo<User> list = this.userService.findByPageInfo(pageNum, pageSize);
MyResponse response = new MyResponse();
if(null != list && list.getList().size() > 0){
response.setCode("success");
response.setMsg("成功");
response.setData(list);
} else {
response.setCode("faild");
response.setMsg("失败");
}
return response;
} @ResponseBody
@RequestMapping(value = "/insert", produces = {"application/json;charset=UTF-8"})
public MyResponse insert(User user){
int result = userService.insert(user);
MyResponse response = new MyResponse();
if(result == 1){
response.setCode("success");
response.setMsg("成功");
} else {
response.setCode("faild");
response.setMsg("失败");
}
return response;
} @ResponseBody
@RequestMapping(value = "/insertSelective", produces = {"application/json;charset=UTF-8"})
public MyResponse insertSelective(User user){
int result = userService.insertSelective(user);
MyResponse response = new MyResponse();
if(result == 1){
response.setCode("success");
response.setMsg("成功");
} else {
response.setCode("faild");
response.setMsg("失败");
}
return response;
} @ResponseBody
@RequestMapping(value = "/deleteByPrimaryKey", produces = {"application/json;charset=UTF-8"})
public MyResponse deleteByPrimaryKey(Integer id){
int result = userService.deleteByPrimaryKey(id);
MyResponse response = new MyResponse();
if(result == 1){
response.setCode("success");
response.setMsg("成功");
} else {
response.setCode("faild");
response.setMsg("失败");
}
return response;
} @ResponseBody
@RequestMapping(value = "/updateByPrimaryKeySelective", produces = {"application/json;charset=UTF-8"})
public MyResponse updateByPrimaryKeySelective(User user){
int result = userService.updateByPrimaryKeySelective(user);
MyResponse response = new MyResponse();
if(result == 1){
response.setCode("success");
response.setMsg("成功");
} else {
response.setCode("faild");
response.setMsg("失败");
}
return response;
} @ResponseBody
@RequestMapping(value = "/updateByPrimaryKey", produces = {"application/json;charset=UTF-8"})
public MyResponse updateByPrimaryKey(User user){
int result = userService.updateByPrimaryKey(user);
MyResponse response = new MyResponse();
if(result == 1){
response.setCode("success");
response.setMsg("成功");
} else {
response.setCode("faild");
response.setMsg("失败");
}
return response;
}
}
最后启动类的代码,在类的前面一定要加注解@MapperScan,里面是*Mapper.java所在包名
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan({"com.hegg.springboot.mapper"})
public class SpringbootApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
} }
spring boot+mybatis+mysql增删改查分页的更多相关文章
- Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例
Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例 一.快速上手 1,配置文件 (1)pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 ...
- (转)Spring Boot (十五): Spring Boot + Jpa + Thymeleaf 增删改查示例
http://www.ityouknow.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html 这篇文章介绍如何使用 Jpa 和 ...
- Spring Boot + Jpa + Thymeleaf 增删改查示例
快速上手 配置文件 pom 包配置 pom 包里面添加 Jpa 和 Thymeleaf 的相关包引用 <dependency> <groupId>org.springframe ...
- spring boot(十五)spring boot+thymeleaf+jpa增删改查示例
快速上手 配置文件 pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 <dependency> <groupId>org.springframework.b ...
- Spring Boot (十五): Spring Boot + Jpa + Thymeleaf 增删改查示例
这篇文章介绍如何使用 Jpa 和 Thymeleaf 做一个增删改查的示例. 先和大家聊聊我为什么喜欢写这种脚手架的项目,在我学习一门新技术的时候,总是想快速的搭建起一个 Demo 来试试它的效果,越 ...
- ssm 框架实现增删改查CRUD操作(Spring + SpringMVC + Mybatis 实现增删改查)
ssm 框架实现增删改查 SpringBoot 项目整合 一.项目准备 1.1 ssm 框架环境搭建 1.2 项目结构图如下 1.3 数据表结构图如下 1.4 运行结果 二.项目实现 1. Emplo ...
- SpringMVC4+MyBatis3+SQLServer 2014 整合(包括增删改查分页)
前言 说起整合自然离开ssm,我本身并不太喜欢ORM,尤其是MyBatis,把SQL语句写在xml里,尤其是大SQL,可读性不高,出错也不容易排查. 开发环境 idea2016.SpringMVC4. ...
- MySQL—增删改查,分组,连表,limit,union,alter,排序,去重
MySQL增删改查 在表格的增删改查中,查的内容是最多的,包括group by ,join,limit,union,alter,排序都是服务于查的 #sql语句数据行操作补充 #增加: #insert ...
- 基于gin的golang web开发:mysql增删改查
Go语言访问mysql数据库需要用到标准库database/sql和mysql的驱动.标准库的Api使用比较繁琐这里再引入另一个库github.com/jmoiron/sqlx. go get git ...
随机推荐
- 十分简便的APK反编译(Mac 版本号 具体解释)
之前參考了网上大神们介绍的apk for mac 的反编译的文章,里面写的十分具体而有用,可是因为apk for mac中反编译细节十分繁琐,过程也相对照较复杂,针对这个缺陷本人对其反编译的过程进行 ...
- union关键字及大小端模式
1. union 关键字 union 维护足够的空间来置放多个数据成员中的“一种”,而不是为每一个数据成员配置空间,在 union 中所有的数据成员共用一个空间,同一时间只能储存其中一个数据成员,所有 ...
- 2016/1/17 private public protected 权限练习
package caipiao; private class Test0117 { private String title; public String actor; protected Strin ...
- 在java程序中,对于数据的输入/输出操作以“流”(stream)方式进行
在java程序中,对于数据的输入/输出操作以“流”(stream)方式进行
- go6---slice切片
package main /* 切片Slice 其本身并不是数组,它指向底层的数组 作为变长数组的替代方案,可以关联底层数组的局部或全部 为引用类型 可以直接创建或从底层数组获取生成 使用len()获 ...
- 【CEOI2002】【Poj 1038】Bugs Integrated, Inc.
http://poj.org/problem?id=1038 发一下中文题面(今天考试直接被改了): 生记茶餐厅由于受杀人事件的影响,生意日渐冷清,不得不暂时歇业.四喜赋闲在家,整天抱着零食看电视,在 ...
- CDN域名集合
akamai-staging.net akamaized.net akamai.net cloudfront.net amazonaws.com azioncdn.net cachefly.net c ...
- nestedScrollview 嵌套使用recyclerview判断滑动到底部 (嵌套滑动导致 不能使用recyclerview的onscrolled监听)
NestedScrollView scroller = (NestedScrollView) findViewById(R.id.myScroll); if (scroller != null) { ...
- Python split 分割中文
str8="中国 和 韩国 的区别" # a=str8.find("Python") # print a b=str8.find("和") ...
- hive 内部表与外部表的区别
hive 内部表: hive> create table soyo55(name STRING,addr STRING,money STRING) row format delimited fi ...