• SpringBoot + MyBatis 结合 MVC框架设计 第1关:项目整合 - SpringBoot + MyBatis


    目录

    任务描述

    相关知识

    使用MyBatis-Spring-Boot-Starter进行整合SpringBoot + MyBatis

    使用SpringBoot + MyBatis编写一个查询用户信息的接口

    编程要求

    测试说明

    参考代码


    任务描述

    本关任务:使用SpringBoot+MyBatis编写一个通过id查询用户信息的小程序。

    相关知识

    MyBatis-Spring-Boot-Starter可帮助你在Spring Boot之上快速构建MyBatis应用程序。为了完成本关任务,你需要掌握:1.使用MyBatis-Spring-Boot-Starter进行整合SpringBoot + MyBatis。2.使用SpringBoot + MyBatis编写一个查询用户信息的接口

    Spring整合MyBatis资料下载:

    https://data.educoder.net/api/attachments/420796

    使用MyBatis-Spring-Boot-Starter进行整合SpringBoot + MyBatis

    博客系统之初识MyBatis中,我们已经学习了如何配置MyBatis,以及通过下列步骤进行访问数据库:

    1. 读取MyBatis核心配置文件;
    2. 通过reader实例化sqlSessionFactory对象;
    3. 创建SqlSession对象;
    4. 执行SqlSession对象执行增改删查操作;
    5. 提交事务;
    6. 释放资源。

    MyBatis提供的MyBatis-Spring-Boot-Starter模块,使上面的步骤变得更简单,它提供了如下功能:

    • 自动检测现有的DataSource

    • 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递;

    • 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例;

    • 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。

    因此我们使用了MyBatis-Spring-Boot-Starter之后,只需要定义一个DataSource即可(application.properties中配置),它会自动创建使用该DataSourceSqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

    是不是很简单、很快捷,接下来让我们来整合吧~首先引入MyBatis-Spring-Boot-Starter依赖:

    1. org.mybatis.spring.boot
    2. mybatis-spring-boot-starter
    3. 2.1.0

    接下来配置application.properties来定义一个DataSource

    1. #mysql驱动
    2. spring.datasource.driverClassName = com.mysql.jdbc.Driver
    3. #mysql地址
    4. spring.datasource.url = jdbc:mysql://localhost:3306/information_schema?useUnicode=true&cha\fracterEncoding=utf-8
    5. #mysql用户名
    6. spring.datasource.username = root
    7. #mysql密码
    8. spring.datasource.password = 123123

    如此整合完成了,接下来我们来使用它吧。

    使用SpringBoot + MyBatis编写一个查询用户信息的接口

    我们先使用注解的方式创建一个mapper接口:

    1. @Mapper
    2. public interface DemoMapper {
    3. @Select("select * from users where userId = #{id}")
    4. Users selectUser(int id);
    5. }

    Users实体类如下:

    1. @Data
    2. public class Users {
    3. private int id;
    4. private String username;
    5. private String password;
    6. }

    接下来让mapper像下面这样注入:

    1. @Controller
    2. public class DemoController {
    3. @Autowired
    4. DemoMapper demoMapper;
    5. @RequestMapping("/query")
    6. @ResponseBody
    7. public Users query(int id) {
    8. Users user = demoMapper.selectUser(id);
    9. return user;
    10. }
    11. }

    最后我们只需要创建一个普通的Spring启动应用程序:

    1. import org.springframework.boot.SpringApplication;
    2. import org.springframework.boot.autoconfigure.SpringBootApplication;
    3. @SpringBootApplication
    4. public class Application {
    5. public static void main(String[] args) {
    6. SpringApplication.run(Application.class, args);
    7. }
    8. }

    让我们来访问这个接口吧:

    编程要求

    请仔细阅读右侧代码,结合相关知识,让我们来编写一个通过id查询用户信息的小程序,请在 Begin-End 区域内进行代码补充以下代码:

    1. 在 pom.xml 里增加MyBatis-Spring-Boot-Starter依赖;
    2. application.properties定义DataSource,用户名和密码前后不要有空格,不然会导致密码错误;
    3. Users中创建用户信息实体类userIduserNamepassWord
    4. DemoMapper增加查询用户信息的数据库访问接口;
    5. DemoController增加前端请求接口,设置请求地址为/query, 调用DemoMapper的接口获取数据库数据。

    t_user(用户信息表):

    | 名称 | 类型 | 注释|主键 |

    | ------------ | ------------ | ------------ |

    | userId | int | 用户ID | Y |

    | userName | varchar | 用户名 | N |

    | passWord | varchar | 用户密码 | N |

    测试说明

    平台将运行你的Java项目,然后访问你编写的网站,访问地址/query,若访问到的数据如下则通过本关。

    1. . ____ _ __ _ _
    2. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
    3. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
    4. \\/ ___)| |_)| | | | | || (_| | ) ) ) )
    5. ' |____| .__|_| |_|_| |_\__, | / / / /
    6. =========|_|==============|___/=/_/_/_/
    7. :: Spring Boot :: (v2.1.8.RELEASE)
    8. Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
    9. 进行查询....
    10. 查询结果:{"userId":1,"userName":"alice","passWord":"0192023A7BBD73250516F069DF18B500"}

    参考代码

    TUser.java

    1. package net.educoder.entity;
    2. import javax.validation.constraints.NotBlank;
    3. import lombok.Data;
    4. @Data
    5. public class TUser {
    6. /********* Begin *********/
    7. /** 用户id **/
    8. private long userId;
    9. /** 用户名称 @NotBlank 为非空 **/
    10. @NotBlank
    11. private String userName;
    12. /** 用户密码 **/
    13. @NotBlank
    14. private String passWord;
    15. /********* End *********/
    16. }

    application.properties

    1. logging.config=classpath:log4j.properties
    2. spring.datasource.initialization-mode=always
    3. /********* Begin *********/
    4. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    5. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/information_schema?characterEncoding=utf-8
    6. spring.datasource.username=root
    7. spring.datasource.password=123123
    8. /********* End *********/

    DemoController.java

    1. package net.educoder.controller;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.ResponseBody;
    6. import net.educoder.entity.TUser;
    7. import net.educoder.mapper.DemoMapper;
    8. @Controller
    9. public class DemoController {
    10. /********* Begin *********/
    11. @Autowired
    12. DemoMapper demoMapper;
    13. @RequestMapping("/query")
    14. @ResponseBody
    15. public TUser query(int id) {
    16. TUser user = demoMapper.selectUser(id);
    17. return user;
    18. }
    19. /********* End *********/
    20. }

    DemoMapper.java

    1. package net.educoder.mapper;
    2. import net.educoder.entity.TUser;
    3. import net.educoder.entity.Users;
    4. import org.apache.ibatis.annotations.Insert;
    5. import org.apache.ibatis.annotations.Mapper;
    6. import org.apache.ibatis.annotations.Options;
    7. import org.apache.ibatis.annotations.Param;
    8. import org.apache.ibatis.annotations.Select;
    9. @Mapper
    10. public interface DemoMapper {
    11. /********* Begin *********/
    12. @Select("select * from t_user where userId = #{id}")
    13. TUser selectUser(@Param("id")int id);
    14. /********* End *********/
    15. }

    pom.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0</modelVersion>
    6. <parent>
    7. <groupId>org.springframework.boot</groupId>
    8. <artifactId>spring-boot-starter-parent</artifactId>
    9. <version>2.1.8.RELEASE</version>
    10. <relativePath /> <!-- lookup parent from repository -->
    11. </parent>
    12. <groupId>net.educoder</groupId>
    13. <artifactId>springbootdemo</artifactId>
    14. <version>0.0.1-SNAPSHOT</version>
    15. <name>demo</name>
    16. <description>Demo project for Spring Boot</description>
    17. <dependencies>
    18. <dependency>
    19. <groupId>org.springframework.boot</groupId>
    20. <artifactId>spring-boot-starter-thymeleaf</artifactId>
    21. <exclusions>
    22. <exclusion>
    23. <groupId>org.springframework.boot</groupId>
    24. <artifactId>spring-boot-starter-logging</artifactId>
    25. </exclusion>
    26. </exclusions>
    27. </dependency>
    28. <dependency>
    29. <groupId>org.springframework.boot</groupId>
    30. <artifactId>spring-boot-starter-log4j2</artifactId>
    31. </dependency>
    32. <dependency>
    33. <groupId>org.springframework.boot</groupId>
    34. <artifactId>spring-boot-starter-web</artifactId>
    35. </dependency>
    36. <!-- Begin -->
    37. <dependency>
    38. <groupId>org.mybatis.spring.boot</groupId>
    39. <artifactId>mybatis-spring-boot-starter</artifactId>
    40. <version>2.1.0</version>
    41. </dependency>
    42. <!-- End -->
    43. <dependency>
    44. <groupId>mysql</groupId>
    45. <artifactId>mysql-connector-java</artifactId>
    46. </dependency>
    47. <dependency>
    48. <groupId>org.projectlombok</groupId>
    49. <artifactId>lombok</artifactId>
    50. </dependency>
    51. </dependencies>
    52. <build>
    53. <plugins>
    54. <plugin>
    55. <groupId>org.springframework.boot</groupId>
    56. <artifactId>spring-boot-maven-plugin</artifactId>
    57. </plugin>
    58. </plugins>
    59. </build>
    60. </project>

  • 相关阅读:
    关于Http和Https
    MyBatis完成增删改查案例(详细代码)
    华为笔记本MateBook D 14 2021款锐龙版R7集显非触屏(NbM-WFP9)原装出厂Windows10-20H2系统
    世界前沿技术发展报告2023《世界航空技术发展报告》(四)无人机技术
    2022-11-03 C++并发编程( 三十九 )
    ccache加速编译速度
    Unity数据加密☀️ 二、使用Rider将C#代码生成DLL文件
    K8S之调度约束+故障排查
    【云原生】Docker可视化监控管理工具使用
    Hadoop HA搭建
  • 原文地址:https://blog.csdn.net/ycq0_9/article/details/127832774