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

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

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数据库表中以EASYMODERATEHARD的形式保存,而不是数值,例如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

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:

确定