目录
使用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中,我们已经学习了如何配置MyBatis,以及通过下列步骤进行访问数据库:
MyBatis核心配置文件;reader实例化sqlSessionFactory对象;SqlSession对象;SqlSession对象执行增改删查操作;MyBatis提供的MyBatis-Spring-Boot-Starter模块,使上面的步骤变得更简单,它提供了如下功能:
自动检测现有的DataSource;
将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递;
将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例;
自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。
因此我们使用了MyBatis-Spring-Boot-Starter之后,只需要定义一个DataSource即可(application.properties中配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。
是不是很简单、很快捷,接下来让我们来整合吧~首先引入MyBatis-Spring-Boot-Starter依赖:
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.0
接下来配置application.properties来定义一个DataSource:
#mysql驱动spring.datasource.driverClassName = com.mysql.jdbc.Driver#mysql地址spring.datasource.url = jdbc:mysql://localhost:3306/information_schema?useUnicode=true&cha\fracterEncoding=utf-8#mysql用户名spring.datasource.username = root#mysql密码spring.datasource.password = 123123
如此整合完成了,接下来我们来使用它吧。
我们先使用注解的方式创建一个mapper接口:
@Mapperpublic interface DemoMapper {@Select("select * from users where userId = #{id}")Users selectUser(int id);}
Users实体类如下:
@Datapublic class Users {private int id;private String username;private String password;}
接下来让mapper像下面这样注入:
@Controllerpublic class DemoController {@AutowiredDemoMapper demoMapper;@RequestMapping("/query")@ResponseBodypublic Users query(int id) {Users user = demoMapper.selectUser(id);return user;}}
最后我们只需要创建一个普通的Spring启动应用程序:
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
让我们来访问这个接口吧:

请仔细阅读右侧代码,结合相关知识,让我们来编写一个通过id查询用户信息的小程序,请在 Begin-End 区域内进行代码补充以下代码:
pom.xml 里增加MyBatis-Spring-Boot-Starter依赖;application.properties定义DataSource,用户名和密码前后不要有空格,不然会导致密码错误;Users中创建用户信息实体类userId、userName、passWord;DemoMapper增加查询用户信息的数据库访问接口;DemoController增加前端请求接口,设置请求地址为/query, 调用DemoMapper的接口获取数据库数据。t_user(用户信息表):
| 名称 | 类型 | 注释|主键 |
| ------------ | ------------ | ------------ |
| userId | int | 用户ID | Y |
| userName | varchar | 用户名 | N |
| passWord | varchar | 用户密码 | N |
平台将运行你的Java项目,然后访问你编写的网站,访问地址/query,若访问到的数据如下则通过本关。
. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) )' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v2.1.8.RELEASE)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.进行查询....查询结果:{"userId":1,"userName":"alice","passWord":"0192023A7BBD73250516F069DF18B500"}
TUser.java
- package net.educoder.entity;
- import javax.validation.constraints.NotBlank;
- import lombok.Data;
- @Data
- public class TUser {
- /********* Begin *********/
- /** 用户id **/
- private long userId;
- /** 用户名称 @NotBlank 为非空 **/
- @NotBlank
- private String userName;
- /** 用户密码 **/
- @NotBlank
- private String passWord;
- /********* End *********/
- }
application.properties
- logging.config=classpath:log4j.properties
- spring.datasource.initialization-mode=always
- /********* Begin *********/
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://127.0.0.1:3306/information_schema?characterEncoding=utf-8
- spring.datasource.username=root
- spring.datasource.password=123123
- /********* End *********/
DemoController.java
- package net.educoder.controller;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import net.educoder.entity.TUser;
- import net.educoder.mapper.DemoMapper;
- @Controller
- public class DemoController {
- /********* Begin *********/
- @Autowired
- DemoMapper demoMapper;
- @RequestMapping("/query")
- @ResponseBody
- public TUser query(int id) {
- TUser user = demoMapper.selectUser(id);
- return user;
- }
- /********* End *********/
- }
DemoMapper.java
- package net.educoder.mapper;
- import net.educoder.entity.TUser;
- import net.educoder.entity.Users;
- import org.apache.ibatis.annotations.Insert;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Options;
- import org.apache.ibatis.annotations.Param;
- import org.apache.ibatis.annotations.Select;
- @Mapper
- public interface DemoMapper {
- /********* Begin *********/
- @Select("select * from t_user where userId = #{id}")
- TUser selectUser(@Param("id")int id);
- /********* End *********/
- }
pom.xml
- <?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 https://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.8.RELEASE</version>
- <relativePath /> <!-- lookup parent from repository -->
- </parent>
- <groupId>net.educoder</groupId>
- <artifactId>springbootdemo</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>demo</name>
- <description>Demo project for Spring Boot</description>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-log4j2</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- Begin -->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.1.0</version>
- </dependency>
- <!-- End -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </project>
