简体   繁体   English

如何处理数据库中没有枚举字段的枚举?

[英]How to handle enumerations without enum fields in a database?

How would I implement a enumeration field in a database that doesn't support enumerations?如何在不支持枚举的数据库中实现枚举字段? (ie SQLite) (即 SQLite)

The fields need to be easily searchable with " field = ?"这些字段需要使用“ field = ?”轻松搜索。 so using any type of data serialization is a bad idea.所以使用任何类型的数据序列化都是一个坏主意。

Using a foreign key to a lookup table is the approach I use.使用查找表的外键是我使用的方法。 In fact, I use this even when I do use a database that supports ENUM (eg MySQL).事实上,即使我确实使用支持 ENUM 的数据库(例如 MySQL),我也会使用它。

For simplicity, I may skip the ever-present " id " for the lookup table, and just use the actual value I need in my main table as the primary key of the lookup table.为简单起见,我可能会跳过查找表中始终存在的“ id ”,而仅使用主表中所需的实际值作为查找表的主键。 That way you don't need to do a join to get the value.这样你就不需要进行连接来获取值。

CREATE TABLE BugStatus (
  status            VARCHAR(20) PRIMARY KEY
);

INSERT INTO BugStatus (status) VALUES ('NEW'), ('OPEN'), ('FIXED');

CREATE TABLE Bugs (
  bug_id            SERIAL PRIMARY KEY,
  summary           VARCHAR(80),
  ...
  status            VARCHAR(20) NOT NULL DEFAULT 'NEW',
  FOREIGN KEY (status) REFERENCES BugStatus(status)
);

Admittedly, storing strings takes more space than MySQL's implementation of ENUM , but unless the table in question has millions of rows, it hardly matters.诚然,存储字符串比 MySQL 的ENUM实现需要更多的空间,但除非有问题的表有数百万行,否则这没什么关系。

Other advantages of the lookup table are that you can add or remove a value from the list with a simple INSERT or DELETE , whereas with ENUM you have to use ALTER TABLE to redefine the list.查找表的其他优点是您可以使用简单的INSERTDELETE从列表中添加或删除值,而使用ENUM您必须使用ALTER TABLE重新定义列表。

Also try querying the current list of permitted values in an ENUM , for instance to populate a pick-list in your user interface.还可以尝试查询ENUM中允许值的当前列表,例如在您的用户界面中填充一个选择列表。 It's a major annoyance!这是一个主要的烦恼! With a lookup table, it's easy: SELECT status from BugStatus .使用查找表,这很容易: SELECT status from BugStatus

Also you can add other attribute columns to the lookup table if you need to (eg to mark choices available only to administrators).如果需要,您还可以将其他属性列添加到查找表中(例如,标记仅对管理员可用的选项)。 In an ENUM , you can't annotate the entries;ENUM ,您不能对条目进行注释; they're just simple values.它们只是简单的值。

Another option besides a lookup table would be to use CHECK constraints (provided the database supports them -- MySQL doesn't support CHECK until version 8.0.16):除了查找表之外的另一个选择是使用CHECK约束(前提是数据库支持它们——MySQL 直到 8.0.16 版本才支持 CHECK):

CREATE TABLE Bugs (
  bug_id            SERIAL PRIMARY KEY,
  summary           VARCHAR(80),
  ...
  status            VARCHAR(20) NOT NULL
    CHECK (status IN ('NEW', 'OPEN', 'FIXED'))
);

But this use of a CHECK constraint suffers from the same disadvantages as the ENUM : hard to change the list of values without ALTER TABLE , hard to query the list of permitted values, hard to annotate values.但是这种CHECK约束的使用与ENUM具有相同的缺点:在没有ALTER TABLE情况下难以更改值列表,难以查询允许值列表,难以注释值。

PS: the equality comparison operator in SQL is a single = . PS:SQL 中的相等比较运算符是单个= The double == has no meaning in SQL.==在 SQL 中没有意义。

To restrict the possible values I would use a foreign key to a table that holds the enumeration items.为了限制可能的值,我将对包含枚举项的表使用外键。

If you don't want to JOIN to do your searches then make the key a varchar if JOINS are not a problem then make the key an INT and don't join unless you need to search on that field.如果您不想 JOIN 进行搜索,则在 JOINS 没有问题的情况下将键设为 varchar,然后将键设为 INT 并且不要加入,除非您需要在该字段上进行搜索。

Note that putting your enumerations in the DB precludes compile time checking of the values in your code (unless you duplicate the enumeration in code.) I have found this to be a large down side.请注意,将您的枚举放在数据库中会阻止编译时检查代码中的值(除非您在代码中复制枚举。)我发现这是一个很大的缺点。

If you use Spring JPA 2.1 or later with hibernate you can implement your own AttributeConverter and define how your enum maps to column values如果您将 Spring JPA 2.1 或更高版本与 hibernate 一起使用,您可以实现您自己的 AttributeConverter 并定义您的枚举如何映射到列值

@Converter(autoApply = true)
public class CategoryConverter implements AttributeConverter<Category, String> {
 
    @Override
    public String convertToDatabaseColumn(Category category) {
        if (category == null) {
            return null;
        }
        return category.getCode();
    }

    @Override
    public Category convertToEntityAttribute(String code) {
        if (code == null) {
            return null;
        }

        return Stream.of(Category.values())
          .filter(c -> c.getCode().equals(code))
          .findFirst()
          .orElseThrow(IllegalArgumentException::new);
    }
}

Please see the 4th solution in the article at Persisting Enums in JPA .The code snippet is also from there.请参阅Persisting Enums in JPA文章中的第四个解决方案。代码片段也来自那里。

You basically have two options :你基本上有两个选择:

  • use an integer field使用整数字段

  • use a varchar field使用 varchar 字段

I would personally advocate the use of varchars, because you won't break anything if you change your enum + the fields are human-readable, but ints have some pro aswell, namely performance (the size of the data is an obvious example)我个人会提倡使用 varchars,因为如果你改变你的枚举 + 字段是人类可读的,你不会破坏任何东西,但 int 也有一些优点,即性能(数据的大小是一个明显的例子)

This is what I did recently这是我最近做的

In my hibernate mapped POJO- I kept the type of the member as String and it is VARCHAR in the database.在我的休眠映射 POJO 中,我将成员的类型保留为 String,它在数据库中为 VARCHAR。

The setter for this takes an enum There is another setter which takes String- but this is private (or you can map the field directly- if that's what you prefer.)这个 setter 需要一个 enum 还有另一个 setter 需要 String - 但这是私有的(或者你可以直接映射字段 - 如果这是你喜欢的。)

Now the fact I am using String is encapsulated from all.现在我使用 String 的事实被全部封装。 For the rest of the application- my domain objects use enum.对于应用程序的其余部分 - 我的域对象使用枚举。 And as far as the database is concerned- I am using String.就数据库而言 - 我正在使用字符串。

If I missed your question- I apologize.如果我错过了您的问题-我深表歉意。

I would use a varchar.我会使用 varchar。 Is this not an option for you?这不是您的选择吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM