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

前言:

本文通过记录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
  • 20
    点赞
  • 100
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
好的,以下是使用Spring Boot和Redis实现增删改查的示例: 1. 添加Redis依赖。在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接。在application.properties文件中添加以下配置: ```properties # Redis服务器地址 spring.redis.host=localhost # Redis服务器连接端口 spring.redis.port=6379 # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器连接密码(默认为空) spring.redis.password= ``` 3. 创建RedisTemplate对象。在配置类中添加以下代码: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` 4. 实现增删改查操作。在服务类中添加以下代码: ```java @Service public class UserService { @Autowired private RedisTemplate<String, Object> redisTemplate; private static final String USER_KEY_PREFIX = "user:"; public void save(User user) { String key = USER_KEY_PREFIX + user.getId(); redisTemplate.opsForValue().set(key, user); } public User getById(Long id) { String key = USER_KEY_PREFIX + id; return (User) redisTemplate.opsForValue().get(key); } public void update(User user) { String key = USER_KEY_PREFIX + user.getId(); redisTemplate.opsForValue().set(key, user); } public void delete(Long id) { String key = USER_KEY_PREFIX + id; redisTemplate.delete(key); } } ``` 以上代码实现了保存、获取、更新和删除用户信息的操作。其中,每个用户信息会以JSON格式存储在Redis中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

瓜仙人

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

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

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

打赏作者

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

抵扣说明:

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

余额充值