SpringBoot+mysql+Redis整合增删改查操作

本文详述了如何使用SpringBoot结合MySQL和Redis进行web项目的增删改查操作,通过创建项目结构、定义User类与UserDao、配置Redis模板类、实现service与Controller,以及详细配置application.yml和pom.xml,最后展示了操作效果。通过Redis作为缓存数据库,以减轻服务器压力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:

本文通过记录SpringBoot+springMVC+redis+mysql来实现web项目中增删改查的具体操作。redis做缓存数据库,针对于频繁需要查询或者解决单点问题都会把数据存到redis来分担服务器压力。

1.项目结构

webdemo1
java
|_________bean
|_________config(redis模板类)
|_________controller
|_________mapper
|_________service
|______Webdemo1Application(springboot启动类)
resources
|_________application.yml
在这里插入图片描述

2.实现步骤

2.1.通过SpringInitializr创建SpringBoot项目。(操作请参考上篇:SpringBoot入门)

2.2创建User类与UserDao

User类:

public class User implements Serializable {
   
   

    private static final long serialVersionUID = 1L;
    private Integer id;
    private String userName;
    private String passWord;
    private Integer sex;
    private Date birthday;
	
	//setter and  getter method    
}

mysql表结构:

create table t_user(
	id int(11) auto_increment comment '编号',
  user_name varchar(50) default '' comment '用户名称',
  pass_word varchar(50) default '' comment '用户密码',
  sex int(3) default null comment '年龄',
  birthday  datetime  comment '生日',
  primary key (id)
)engine=innodb auto_increment =1 comment '用户表';

UserDao类:

@Repository
@Mapper
public interface UserDao {
   
   
    //用户列表
    @Select("select * from t_user")
    @Results({
   
   
            @Result(property = "userName",column = "user_name"),
            @Result(property = "passWord",column = "pass_word")
    })
    List<User> queryAll();
    //根据id获取user
    @Select("select * from t_user where id =#{id}")
    @Results({
   
   
            @Result(property = "userName",column = "user_name"),
            @Result(property = "passWord",column = "pass_word")
    })
    User findUserById(Integer id);
    //根据id修改user
    @Update("update t_user set user_name=#{userName},pass_word =#{passWord},sex=#{sex},birthday=#{birthday} WHERE id = #{id} ")
    int updateUser(User user);
    //根据id删除用户
    @Delete("delete from t_user where id = #{id}")
    int deleteUserById(Integer id);
}

2.3创建RedisConfig模板类

/**
 * 配置redistemplate序列化
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
   
   

    /**
     * 选择redis作为默认缓存工具
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
   
   
        //设置缓存有效一小时
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.
                defaultCacheConfig().entryTtl(Duration.ofHours(1));
        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瓜仙人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值