spring boot+mybatis+mysql增删改查分页
server: port: 8081 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); } }