gpt4 book ai didi

java - 在 Hibernate 和 Spring 中初始化枚举

转载 作者:行者123 更新时间:2023-12-02 02:40:23 24 4
gpt4 key购买 nike

我有一个简单的类(class)

@Entity
@Table(name="user")
public class User implements Serializable {

@Id
@GeneratedValue
private Integer Id;
@Length(min = 5, message = "Username must be at least 5 characters long.")
@Column(name="username",nullable=false,unique=true)
private String userName;
@ManyToMany(cascade= {CascadeType.PERSIST},fetch=FetchType.EAGER)
@JoinTable(name="user_user_profile")
private Set<UserProfile> userProfile = new HashSet<>();
}

第二类:

@Entity
@Table(name = "user_profile")
public class UserProfile {
@javax.persistence.Id
@GeneratedValue
private int Id;

@Column(name = "type", nullable = false, unique = true)
@Enumerated(EnumType.STRING)
private UserProfileType type = UserProfileType.USER;
}

public enum UserProfileType {
USER("USER"),
ADMIN("ADMIN");
}

我正在将 Spring MVC 和 Spring Secuirty 与 Hibernate 结合使用。有什么方法可以在应用程序启动时在 UserProfile 实体中输入所有可能的条目(只有两个)?我是否必须从数据库获取 UserProfile (通过 TypedQueryEntityManager.find() ),然后将其添加到 User 中以不进行任何操作异常(exception)吗?

最佳答案

枚举项在您的应用程序中是静态的,因此我不会尝试在数据库中进行自动更改。添加新记录很简单,但删除已引用的项目可能需要单独处理。这些值对于您的应用程序至关重要,因此我认为它们应该包含在您的 SQL 脚本中。

如果您使用 Flyway 或 Liquibase 等数据库版本控制工具,请在迁移脚本中添加/删除 user_profile 表的记录。它们可以配置为在应用程序(和 Hibernate)启动之前运行迁移,因此应用程序将始终看到正确的数据。

关于java - 在 Hibernate 和 Spring 中初始化枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45586803/

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