如何在Java应用程序的数据库中高效地保留枚举值?

huangapple go评论101阅读模式
英文:

How to keep enum values most efficiently in database for Java apps?

问题

我在实体类中如下所示实现枚举类:

枚举:

  1. public enum Difficulty {
  2. EASY,
  3. MODERATE,
  4. HARD;
  5. }

实体类:

  1. @Entity
  2. public class Recipe {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private Long id;
  6. @Column(nullable = false, length = 50)
  7. private String title;
  8. @Column(nullable = false)
  9. @Enumerated(value = EnumType.STRING)
  10. private Difficulty difficulty;
  11. }

然而,这些枚举值在PostgreSQL数据库表中以EASYMODERATEHARD的形式保存,而不是数值,例如1、2、3。当我需要使用枚举而不是为此Difficulty枚举创建查找表时,是否有更好的Java应用程序方法?

英文:

I implement enum classes in my entities as shown below:

enum:

  1. public enum Difficulty {
  2. EASY,
  3. MODERATE,
  4. HARD;
  5. }

entity:

  1. @Entity
  2. public class Recipe {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private Long id;
  6. @Column(nullable = false, length = 50)
  7. private String title;
  8. @Column(nullable = false)
  9. @Enumerated(value = EnumType.STRING)
  10. private Difficulty difficulty;
  11. }

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

  1. `@Enumerated(value = EnumType.STRING)`中的数值移除然后枚举的序数值将会被写入数据库中
  2. @Entity
  3. public class Recipe {
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.IDENTITY)
  6. private Long id;
  7. @Column(nullable = false, length = 50)
  8. private String title;
  9. @Column(nullable = false)
  10. @Enumerated
  11. private Difficulty difficulty;
  12. }
  13. 但请记住重新排序或在中间添加新的枚举值会破坏功能因为数字被映射到枚举值的其他位置
英文:

Remove the value in@Enumerated(value = EnumType.STRING) then the ordinal values will be written into the database

  1. @Entity
  2. public class Recipe {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private Long id;
  6. @Column(nullable = false, length = 50)
  7. private String title;
  8. @Column(nullable = false)
  9. @Enumerated
  10. private Difficulty difficulty;
  11. }

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

huangapple
  • 本文由 发表于 2023年2月24日 14:25:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553227.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定