【问题标题】:Dynamically create columns from Enums in Spring boot application在 Spring Boot 应用程序中从 Enums 动态创建列
【发布时间】:2020-05-17 14:41:32
【问题描述】:

我有一个枚举 NotificationType。我想使用枚举常量作为列名创建实体“用户”。 目前我必须手动编写列名。有没有办法从枚举自动创建列。

NotificationType.java

public enum NotificationType {
    EVENT,
    HELP,
    HOLIDAY
}

User.java

import javax.persistence.Column;
import javax.persistence.Entity;
@Entity
public class User {

    @Column(nullable = false)
    private String EVENT;

    @Column(nullable = false)
    private String HELP;

    @Column(nullable = false)
    private String HOLIDAY;
}

【问题讨论】:

  • 为什么一个用户表会包含不同的通知类型列?
  • @123 实际上我需要在用户表中存储多个通知类型。目前我正在将所有通知类型创建为列并将 1 和 0 存储为存在或不存在。
  • 为什么没有通知类型表...
  • 我会试试的

标签: java spring-boot jpa enums


【解决方案1】:

不要,而是创建一个 'user_notifications' 表 - 例如

CREATE TABLE user_notifications
(
user_id            UUID not null,
notification_type  varchar(255) not null,
timestamp          timestamp not null,
payload            text not null
);
ALTER TABLE user_notifications ADD CONSTRAINT user_notifications_user_id FOREIGN KEY (user_id) REFERENCES users (user_id);

'payload' 可以是 JSON,一个标志,任何你想要的 - 但 JSON 是最灵活的,因为你可以在不更改数据库架构的情况下向通知添加更多信息。

【讨论】:

    猜你喜欢
    • 2019-11-22
    • 1970-01-01
    • 2017-07-04
    • 2016-07-04
    • 2018-08-03
    • 2021-03-18
    • 2020-03-30
    • 1970-01-01
    • 2019-07-24
    相关资源
    最近更新 更多