Spring在nodejs中的实体

Spring's Entity inside nodejs

我过去在后端管理持久状态的方式是使用 Spring 的 @Entity。基本上,我像这样定义一个常规 java class:

@Entity
@Table(name = "users")
class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    public Long user_id;

    @Column(name = "email")
    public String email;
}

然后我可以使用 Hibernate 检索托管 java 对象:

User user = userFactory.getUserFromId(3L); // uses Hibernate internally to get a managed instance
user.email = "abc@company.com"; // gets auto-save to mysql database

这非常方便,因为我可以只更改字段而不必明确担心保存数据。这也很方便,因为我可以指定一些字段作为索引,所以我可以非常快速地搜索匹配的电子邮件名称。

我将如何使用 NodeJS 做同样的事情?我需要使用节点,因为我的团队根本不熟悉 Java。我希望能够快速存储复杂的 json 对象,在内存中有一个缓存版本,理想情况下可以定期永久存储数据。

我目前的计划是为此使用Redis。获取用户对象应如下所示:

class User {
    constructor(json) {
        this.json = json
    }

    async save() {
        await redis.set(JSON.stringify(this.json));
    }
}

async function user(id) {
    let json = JSON.parse(await redis.get("user-" + id));
    return User(json);
}

u3 = await user(3);
u3.json.email = "def@company.com";
u3.save();

为了按名称获取用户,我将创建自己的索引(从电子邮件映射到用户 ID),并可能将此索引也存储在 redis 中。

所有这些看起来都很笨拙,感觉就像我在重新实现基本的数据库功能。那么在我这样做之前,是否有不同的方法可以在js中很好地管理json对象,从而使编码体验与在Spring中有些相同?

您需要的是 ORM,即可以将您的对象映射到数据库记录的每种语言的工具。

通过快速搜索,您可以找到在 NodeJS 世界中非常流行的 Sequalize