gpt4 book ai didi

spring boot data redis如何将hashmap更改为Model

转载 作者:可可西里 更新时间:2023-11-01 11:36:51 24 4
gpt4 key购买 nike

刚开始接触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,包含Model User 的字段,现在我想将userMap 更改为Model User

我该怎么办?

提前致谢。

最佳答案

  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);

关于spring boot data redis如何将hashmap更改为Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31826958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com