精通 Spring Boot 系列 13

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 RDS MySQL Serverless,价值2615元额度,1个月
简介: 精通 Spring Boot 系列 13

阅读全文,约 14 分钟

这是江帅帅的第014篇原创

Spring Boot 整合 MyBatis

MyBatis 是目前优秀的 ORM 框架,支持普通的数据库操作,几乎消除了常规的 JDBC 操作,极大简化我们的开发操作。

1)编辑 pom.xml 文件
<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>
 
    <groupId>com.nx</groupId>
    <artifactId>springbootdata</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/>
    </parent>
 
    <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>
        <!-- 添加spring-boot-starter-web模块依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <!-- 添加spring-boot-starter-thymeleaf模块依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
 
        <!-- 添加MySQL依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
 
        <!-- 添加MyBatis依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
 
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
2)编辑 application.properties 文件
####################
### 数据源信息配置 ###
####################
# 数据库地址
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
# 用户名
spring.datasource.username=root
# 密码
spring.datasource.password=1234
# 数据库驱动
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
# 指定连接池中最大的活跃连接数.
spring.datasource.max-active=20
# 指定连接池最大的空闲连接数量.
spring.datasource.max-idle=8
# 指定必须保持连接的最小值
spring.datasource.min-idle=8
# 指定启动连接池时,初始建立的连接数量
spring.datasource.initial-size=10
3)创建 User 持久化类
public class User implements Serializable{
 
    private static final long serialVersionUID = 1L;
 
    private int id ;
    private String loginName ;
    private String username ;
    private String password;
 
    // setXxx 和 getXxx 方法
}
4)创建 UserRepository 数据访问接口
public interface UserRepository {
 
    @Insert("insert into tb_user(login_name ,username ,password) "
                + "values (#{loginName},#{username},#{password})")
    public int insertUser(User user);
 
    // 插入数据获取主键
    @Insert("insert into tb_user(login_name ,username ,password) "
            + "values (#{loginName},#{username},#{password})")
    @Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")
    public void insertGetKey(User user);
 
 
    @Select("select * from tb_user where username = #{username}")
    // 引用id="userResult"的@Results
    @ResultMap("userResult")
    public User selectByUsername(@Param("username")String username);
 
    @Select("select * from tb_user")
    // @Results用于映射对象属性和数据库列,常用于对象属性和数据库列不同名情况
    @Results(id="userResult",value={
            @Result(id=true,column="id",property="id"),
            @Result(column="login_name",property="loginName"),
            @Result(column="password",property="password"),
            @Result(column="username",property="username")
        })
    public List<User> findAll();
 
 
    @Delete("delete from tb_user where id=#{id}")
    public void delete(final Integer id);
 
 
    @Select("select * from tb_user where id=#{id}")
    // 引用id="userResult"的@Results
    @ResultMap("userResult")
    public User findUserById(int id);
 
    @Update("update tb_user set username=#{username}, login_name=#{loginName} where id=#{id}")
    public void update(final User user);
}
5)创建 UserService 业务层类
@Service
public class UserService {
 
    // 注入UserRepository
    @Resource
    private UserRepository userRepository;
 
    public int insertUser(User user){
        return userRepository.insertUser(user);
    }
 
    public User selectByUsername(String username){
        return userRepository.selectByUsername(username);
    }
 
    public List<User> findAll(){
        return userRepository.findAll();
    }
 
    public void insertGetKey(User user) {
        userRepository.insertGetKey(user);
    }
 
    public void update(User user) {
        userRepository.update(user);
    }
 
    public void delete(Integer id) {
        userRepository.delete(id);
    }
}
6)创建 UserController 控制器类
@RestController
@RequestMapping("/user")
public class UserController {
 
    // 注入UserService
    @Resource
    private UserService userService;
 
    @RequestMapping("/insertUser")
    public String insertUser(User user){
        return "插入数据["+userService.insertUser(user)+"]条";
    }
 
    @RequestMapping("/insertGetKey")
    public User insertGetKey(User user) {
        userService.insertGetKey(user);
        return user ;
    }
 
    @RequestMapping("/selectByUsername")
    public User selectByUsername(String username){
        return userService.selectByUsername(username);
    }
 
    @RequestMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }
 
    @RequestMapping("/update")
    public void update(User user) {
        userService.update(user);
    }
 
    @RequestMapping("/delete")
    public void delete(Integer id) {
        userService.delete(id);
    }
}
7)测试

http://localhost:8080/user/insertUser?loginName=shuaishuai&username=帅帅&password=123123


相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
8月前
|
Java 数据格式 Docker
Spring Boot
Spring Boot 入门
131 0
|
12天前
|
Java 关系型数据库 数据库连接
精通 Spring Boot 系列 07
精通 Spring Boot 系列 07
18 0
|
12天前
|
Java 数据库 Spring
精通 Spring Boot 系列 12
精通 Spring Boot 系列 12
24 0
|
12天前
|
Java Spring
精通 Spring Boot 系列 10
精通 Spring Boot 系列 10
23 0
|
12天前
|
Java Spring 容器
精通 Spring Boot 系列 02
精通 Spring Boot 系列 02
7 0
|
12天前
|
存储 安全 Java
精通 Spring Boot 系列 15
精通 Spring Boot 系列 15
23 0
|
12天前
|
Java Spring
精通 Spring Boot 系列 09
精通 Spring Boot 系列 09
23 0
|
7月前
|
Cloud Native Java Go
《Spring Boot前世今生》
《Spring Boot前世今生》
26 0
|
10月前
|
Java Spring
Spring Boot 3.0
Spring Boot 3.0
572 0
|
XML 监控 Java
初学Spring Boot 必须要知道的事
Spring Boot简介 Spring Boot 核心功能 Spring Boot的优缺点 SpringBoot 常用注解和原理
138 0