Spring Boot2 + Mybatis 整合(Mybatis自动生成插件、分页插件)

版权声明:转载注明出处 https://blog.youkuaiyun.com/jy02268879/article/details/83065648

内容:

Spring Boot2 + Mybatis 整合

Mybatis Generator自动生成代码

Mybatis PageHelper分页插件

创建maven项目

修改pom.xml 注意springboot、druid、pageHelper的版本号

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.sid</groupId>
  6. <artifactId>springboot</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.0.5.RELEASE</version>
  13. <relativePath/> <!-- lookup parent from repository -->
  14. </parent>
  15. <properties>
  16. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  17. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  18. <java.version>1.8</java.version>
  19. </properties>
  20. <dependencies>
  21. <!-- spring-boot的web启动的jar包 -->
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-web</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-test</artifactId>
  29. <scope>test</scope>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.apache.commons</groupId>
  33. <artifactId>commons-lang3</artifactId>
  34. <version>3.4</version>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.mybatis.spring.boot</groupId>
  38. <artifactId>mybatis-spring-boot-starter</artifactId>
  39. <version>1.3.2</version>
  40. </dependency>
  41. <dependency>
  42. <groupId>mysql</groupId>
  43. <artifactId>mysql-connector-java</artifactId>
  44. <version>5.1.38</version>
  45. </dependency>
  46. <!-- alibaba的druid数据库连接池 -->
  47. <dependency>
  48. <groupId>com.alibaba</groupId>
  49. <artifactId>druid-spring-boot-starter</artifactId>
  50. <version>1.1.9</version>
  51. </dependency>
  52. <!-- 分页插件-->
  53. <dependency>
  54. <groupId>com.github.pagehelper</groupId>
  55. <artifactId>pagehelper-spring-boot-starter</artifactId>
  56. <version>1.2.5</version>
  57. </dependency>
  58. </dependencies>
  59. <build>
  60. <plugins>
  61. <plugin>
  62. <groupId>org.springframework.boot</groupId>
  63. <artifactId>spring-boot-maven-plugin</artifactId>
  64. </plugin>
  65. <!-- mybatis generator 自动生成代码插件 -->
  66. <plugin>
  67. <groupId>org.mybatis.generator</groupId>
  68. <artifactId>mybatis-generator-maven-plugin</artifactId>
  69. <version>1.3.2</version>
  70. <configuration>
  71. <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
  72. <overwrite>true</overwrite>
  73. <verbose>true</verbose>
  74. </configuration>
  75. </plugin>
  76. </plugins>
  77. </build>
  78. </project>

创建启动类App.java

  1. package com.sid;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. @MapperScan("com.sid.mapper")//将项目中对应的mapper类的路径加进来就可以了
  7. public class App {
  8. public static void main(String[] args) {
  9. SpringApplication.run(App.class, args);
  10. }
  11. }

创建application.yml

  1. server:
  2. port: 8088
  3. servlet:
  4. context-path: /sid
  5. spring:
  6. mvc:
  7. view:
  8. prefix: /
  9. suffix: .html
  10. datasource:
  11. url: jdbc:mysql://localhost:3306/sid
  12. username: root
  13. password: root
  14. # 使用druid数据源
  15. type: com.alibaba.druid.pool.DruidDataSource
  16. driver-class-name: com.mysql.jdbc.Driver
  17. ## 该配置节点为独立的节点,不是在在spring的节点下
  18. mybatis:
  19. mapper-locations: classpath:mapping/*.xml #注意:一定要对应mapper映射xml文件的所在路径
  20. type-aliases-package: com.sid.model # 注意:对应实体类的路径
  21. configuration:
  22. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #控制台打印sql
  23. #pagehelper分页插件
  24. pagehelper:
  25. helperDialect: mysql
  26. reasonable: true
  27. supportMethodsArguments: true
  28. params: count=countSql

在resources/generator下创建文件generatorConfig.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6. <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
  7. <classPathEntry location="F:\MySQL\Connector.J 5.1\mysql-connector-java-5.1.38-bin.jar"/>
  8. <context id="DB2Tables" targetRuntime="MyBatis3">
  9. <commentGenerator>
  10. <property name="suppressDate" value="true"/>
  11. <!-- 是否去除自动生成的注释 true:是 : false:否 -->
  12. <property name="suppressAllComments" value="true"/>
  13. </commentGenerator>
  14. <!--数据库链接URL,用户名、密码 -->
  15. <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/sid" userId="root" password="root">
  16. </jdbcConnection>
  17. <javaTypeResolver>
  18. <property name="forceBigDecimals" value="false"/>
  19. </javaTypeResolver>
  20. <!-- 生成模型的包名和位置-->
  21. <javaModelGenerator targetPackage="com.sid.model" targetProject="src/main/java">
  22. <property name="enableSubPackages" value="true"/>
  23. <property name="trimStrings" value="true"/>
  24. </javaModelGenerator>
  25. <!-- 生成映射文件的包名和位置-->
  26. <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
  27. <property name="enableSubPackages" value="true"/>
  28. </sqlMapGenerator>
  29. <!-- 生成DAO的包名和位置-->
  30. <javaClientGenerator type="XMLMAPPER" targetPackage="com.sid.mapper" targetProject="src/main/java">
  31. <property name="enableSubPackages" value="true"/>
  32. </javaClientGenerator>
  33. <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
  34. <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
  35. </context>
  36. </generatorConfiguration>

项目目录

 

数据库中的表

  1. CREATE TABLE `user` (
  2. `id` bigint(32) NOT NULL COMMENT '用户ID',
  3. `name` varchar(30) NOT NULL COMMENT '用户名',
  4. `password` varchar(30) NOT NULL COMMENT '密码',
  5. `mobile_phone` varchar(20) NOT NULL COMMENT '手机号',
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

mybatis自动生成代码的插件使用方式

run

然会就会自动生成UserMapper.xml、 User.java 、UserMapper.java

 

UserController.java

  1. package com.sid.controller;
  2. import com.github.pagehelper.PageInfo;
  3. import com.sid.model.User;
  4. import com.sid.service.UserService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. @Controller
  10. @RequestMapping(value = "/user")
  11. public class UserController {
  12. @Autowired
  13. private UserService userService;
  14. @ResponseBody
  15. @RequestMapping(value = "/add")
  16. public int addUser(User user){
  17. return userService.addUser(user);
  18. }
  19. @ResponseBody
  20. @RequestMapping(value = "/delete")
  21. public int deleteUser(String id){
  22. return userService.deleteUser(id);
  23. }
  24. @ResponseBody
  25. @RequestMapping(value = "/update")
  26. public int updateUser(User user){
  27. return userService.updateUser(user);
  28. }
  29. @ResponseBody
  30. @RequestMapping(value = "/selectAll")
  31. public PageInfo<User> selectAll(int pageNum, int pageSize){
  32. return userService.selectAll( pageNum, pageSize);
  33. }
  34. }

 

UserService.java

  1. package com.sid.service;
  2. import com.github.pagehelper.PageInfo;
  3. import com.sid.model.User;
  4. public interface UserService {
  5. int addUser(User user);
  6. int deleteUser(String id);
  7. int updateUser(User user);
  8. /*
  9. * pageNum 开始页数
  10. * pageSize 每页显示的数据条数
  11. * */
  12. PageInfo<User> selectAll(int pageNum, int pageSize);
  13. }

UserServiceImpl.java

  1. package com.sid.service.impl;
  2. import com.github.pagehelper.PageHelper;
  3. import com.github.pagehelper.PageInfo;
  4. import com.sid.mapper.UserMapper;
  5. import com.sid.model.User;
  6. import com.sid.service.UserService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import java.util.List;
  10. @Service(value = "userService")
  11. public class UserServiceImpl implements UserService {
  12. @Autowired
  13. private UserMapper userMapper;
  14. @Override
  15. public int addUser(User user) {
  16. return userMapper.insertSelective(user);
  17. }
  18. @Override
  19. public int deleteUser(String id) {
  20. return userMapper.deleteByPrimaryKey(id);
  21. }
  22. @Override
  23. public int updateUser(User user) {
  24. return userMapper.updateByPrimaryKey(user);
  25. }
  26. /*
  27. * pageNum 开始页数
  28. * pageSize 每页显示的数据条数
  29. * */
  30. @Override
  31. public PageInfo<User> selectAll(int pageNum, int pageSize) {
  32. PageHelper.startPage(pageNum, pageSize,"id desc"); //开始起始页
  33. List<User> userList = userMapper.selectAll(); // 获取数据
  34. PageInfo<User> page = new PageInfo<>(userList); // 实例化PageInfo
  35. return page;
  36. }
  37. }

UserMapper.java

  1. package com.sid.mapper;
  2. import com.sid.model.User;
  3. import org.springframework.stereotype.Component;
  4. import java.util.List;
  5. @Component
  6. public interface UserMapper {
  7. int deleteByPrimaryKey(String id);
  8. int insert(User record);
  9. int insertSelective(User record);
  10. User selectByPrimaryKey(String id);
  11. int updateByPrimaryKeySelective(User record);
  12. int updateByPrimaryKey(User record);
  13. List<User> selectAll();
  14. }

UserMapping.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="com.sid.mapper.UserMapper" >
  4. <resultMap id="BaseResultMap" type="com.sid.model.User" >
  5. <id column="id" property="id" jdbcType="BIGINT" />
  6. <result column="name" property="name" jdbcType="VARCHAR" />
  7. <result column="password" property="password" jdbcType="VARCHAR" />
  8. <result column="mobile_phone" property="mobilePhone" jdbcType="VARCHAR" />
  9. </resultMap>
  10. <sql id="Base_Column_List" >
  11. id, name, password, mobile_phone
  12. </sql>
  13. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
  14. select
  15. <include refid="Base_Column_List" />
  16. from user
  17. where id = #{id,jdbcType=BIGINT}
  18. </select>
  19. <select id="selectAll" resultMap="BaseResultMap" >
  20. select
  21. <include refid="Base_Column_List" />
  22. from user
  23. </select>
  24. <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
  25. delete from user
  26. where id = #{id,jdbcType=BIGINT}
  27. </delete>
  28. <insert id="insert" parameterType="com.sid.model.User" >
  29. insert into user (id, name, password,
  30. mobile_phone)
  31. values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
  32. #{mobilePhone,jdbcType=VARCHAR})
  33. </insert>
  34. <insert id="insertSelective" parameterType="com.sid.model.User" >
  35. insert into user
  36. <trim prefix="(" suffix=")" suffixOverrides="," >
  37. <if test="id != null" >
  38. id,
  39. </if>
  40. <if test="name != null" >
  41. name,
  42. </if>
  43. <if test="password != null" >
  44. password,
  45. </if>
  46. <if test="mobilePhone != null" >
  47. mobile_phone,
  48. </if>
  49. </trim>
  50. <trim prefix="values (" suffix=")" suffixOverrides="," >
  51. <if test="id != null" >
  52. #{id,jdbcType=BIGINT},
  53. </if>
  54. <if test="name != null" >
  55. #{name,jdbcType=VARCHAR},
  56. </if>
  57. <if test="password != null" >
  58. #{password,jdbcType=VARCHAR},
  59. </if>
  60. <if test="mobilePhone != null" >
  61. #{mobilePhone,jdbcType=VARCHAR},
  62. </if>
  63. </trim>
  64. </insert>
  65. <update id="updateByPrimaryKeySelective" parameterType="com.sid.model.User" >
  66. update user
  67. <set >
  68. <if test="name != null" >
  69. name = #{name,jdbcType=VARCHAR},
  70. </if>
  71. <if test="password != null" >
  72. password = #{password,jdbcType=VARCHAR},
  73. </if>
  74. <if test="mobilePhone != null" >
  75. mobile_phone = #{mobilePhone,jdbcType=VARCHAR},
  76. </if>
  77. </set>
  78. where id = #{id,jdbcType=BIGINT}
  79. </update>
  80. <update id="updateByPrimaryKey" parameterType="com.sid.model.User" >
  81. update user
  82. set name = #{name,jdbcType=VARCHAR},
  83. password = #{password,jdbcType=VARCHAR},
  84. mobile_phone = #{mobilePhone,jdbcType=VARCHAR}
  85. where id = #{id,jdbcType=BIGINT}
  86. </update>
  87. </mapper>

User.java

  1. package com.sid.model;
  2. public class User {
  3. private Long id;
  4. private String name;
  5. private String password;
  6. private String mobilePhone;
  7. public Long getId() {
  8. return id;
  9. }
  10. public void setId(Long id) {
  11. this.id = id;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name == null ? null : name.trim();
  18. }
  19. public String getPassword() {
  20. return password;
  21. }
  22. public void setPassword(String password) {
  23. this.password = password == null ? null : password.trim();
  24. }
  25. public String getMobilePhone() {
  26. return mobilePhone;
  27. }
  28. public void setMobilePhone(String mobilePhone) {
  29. this.mobilePhone = mobilePhone == null ? null : mobilePhone.trim();
  30. }
  31. }

添加11条数据到数据库中

查询

结果

打开mybatis执行的SQL打印会在后台看见

还是执行了一次select count(0)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值