【问题标题】:spring boot data redis how to change hashmap to a Modelspring boot data redis如何将hashmap更改为Model
【发布时间】:2015-10-27 21:38:14
【问题描述】:

我是spring和spring boot的新手,现在用的是spring data redis。

  1. 我有一个这样的模型

    @Entity
    @Table(name = "users")
    public class User {
        private Long id;
    
        @Id
        @javax.persistence.Column(name = "id", nullable = false, insertable = true, updatable = true)
    
        private String email;
    
        @Basic
        @javax.persistence.Column(name = "email", nullable = false, insertable = true, updatable = true, length = 128)
    
       //some other fields and getters and setters
    
    }
    
  2. 在redis中,我们使用哈希存储用户模型,像这样。 关键是:u_id

    redis-cli> hgetall u_19999
      1) "id"
      2) "19999"
      3) "email"
      4) "xx@gmail.com"
      5) "weblink"
      6) "www.google.com"
    
  3. 在spring boot数据redis中

    HashOperations<String, String, String> hashOperations = this.stringRedisTemplate.opsForHash();
    String key = "u_"+userId;
    Map<String, String> userMap = hashOperations.entries(key);
    

现在,userMap 是一个 hashmap,包含模型用户的字段,现在我想将 userMap 更改为模型用户

我该怎么办?

提前致谢。

【问题讨论】:

    标签: spring redis spring-boot spring-data


    【解决方案1】:
    1. 首先得到所有字段

       HashOperations<String, String, String> hashOperations =            this.stringRedisTemplate.opsForHash();
       String key = "u_"+userId;
       Map<String, String> userMap = hashOperations.entries(key);
      
    2. 使用BeanUtilsHashMapper

      HashMapper<User, String, String> mapper = new BeanUtilsHashMapper<User>(User.class);
      return mapper.fromHash(userMap);
      

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 1970-01-01
      • 2022-12-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      相关资源
      最近更新 更多