英文:
How to keep enum values most efficiently in database for Java apps?
问题
我在实体类中如下所示实现枚举类:
枚举:
public enum Difficulty {
EASY,
MODERATE,
HARD;
}
实体类:
@Entity
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 50)
private String title;
@Column(nullable = false)
@Enumerated(value = EnumType.STRING)
private Difficulty difficulty;
}
然而,这些枚举值在PostgreSQL数据库表中以EASY
、MODERATE
或HARD
的形式保存,而不是数值,例如1、2、3。当我需要使用枚举而不是为此Difficulty
枚举创建查找表时,是否有更好的Java应用程序方法?
英文:
I implement enum classes in my entities as shown below:
enum:
public enum Difficulty {
EASY,
MODERATE,
HARD;
}
entity:
@Entity
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 50)
private String title;
@Column(nullable = false)
@Enumerated(value = EnumType.STRING)
private Difficulty difficulty;
}
However, these enum values are kept in PostgreSQL database table as EASY
, MODERATE
or HARD
instead of a numeric values e.g. 1, 2, 3. When I need to use enum instead of creating a lookup table for this Difficulty
enum, it there a better approach for Java apps?
答案1
得分: 0
将`@Enumerated(value = EnumType.STRING)`中的数值移除,然后枚举的序数值将会被写入数据库中。
@Entity
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 50)
private String title;
@Column(nullable = false)
@Enumerated
private Difficulty difficulty;
}
但请记住,重新排序或在中间添加新的枚举值会破坏功能,因为数字被映射到枚举值的其他位置。
英文:
Remove the value in@Enumerated(value = EnumType.STRING)
then the ordinal values will be written into the database
@Entity
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 50)
private String title;
@Column(nullable = false)
@Enumerated
private Difficulty difficulty;
}
But keep in mind, that reordering or adding a new enum value in the middle will breaks the functionality, because the number is mapped to an other in enum value
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论