SpringBoot整合Mysql、Redis


一、项目创建

1.1 创建项目

  • 在IDEA中,File--New--Project--Spring Initializer
  • 名称为springboot-mysql-redis

1.2 目录结构

1.3 pom.xml配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
    username: root
    password: 1234

  redis:
    host: localhost
    port: 6379
    password: 1234


server:
  port: 8080

mybatis:
  mapper-locations: classpath:mapper/*xml
  type-aliases-package: com.xsbc.entity
  # 开启驼峰命名
  configuration:
    map-underscore-to-camel-case: true

二、初始化数据库

drop database if exists blog;
create database blog;
user blog;
drop table if exists user;
create table user(
    id int(11) not null,
    name varchar(255) DEFAULT "",
    age int(11) DEFAULT 0,
    PRIMARY KEY(id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

insert into user values(1,'小王',20);
insert into user values(2,'老李',23);

三、初始化代码

3.1 实体类entity

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private int age;
}

3.2 Mapper接口类

@Mapper
public interface UserMapper {
    List<User> getAllUsers();
    int updateUser(Integer id);
}
  • 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.xsbc.mapper.UserMapper">
    <select id="getAllUsers" resultType="com.xsbc.entity.User">
        select * from user
    </select>

    <!--   User类的id参数是int类型,mysql默认是Integer -->
    <update id="updateUserAgeById" parameterType="java.lang.Integer">
        update user set age=age+2 where id=#{id}
    </update>
</mapper>

3.3 Redis工具类


原文链接:https://blog.csdn.net/Jiangtagong/article/details/122960915?utm_medium=distribute.pc_feed_blog.none-task-blog-hot_rank_bottoming-7.nonecasedepth_1-utm_source=distribute.pc_feed_blog.none-task-blog-hot_rank_bottoming-7.nonecase