枚举数据库中的常量和动态值 [英] Enum with constant and also dynamic values from database

查看:179
本文介绍了枚举数据库中的常量和动态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前的状态是枚举 MyType表示类型表,其列为:

I have a current state where an enum MyType represent Type table with columns as:

ID
Name

使用ID参数识别类型使用 byId 方法:

And it's used to identify type using ID parameter with byId method:

public enum MyType {

FIRST_TYPE("First Type", 10),
SECOND_TYPE("Second Type", 20);
public static class Holder {
    static Map<Integer, MyType > idMap = new HashMap<>();
    private Holder() { }
}

private MyType(String name, Integer id) {
    this.name = name;
    this.id = id;
    Holder.idMap.put(id, this);
}

public String getName() {
    return name;
}

public static MyType byId(Integer id) {
    return Holder.idMap.get(id);
}

我的新要求是支持Type表中还存在值,我发现<一个用于动态枚举的href = https://stackoverflow.com/questions/851466/populate-an-enum-with-values-from-data>>答案,但接受答案不是这么做

My new requirement is to support also values exists in Type table, I found answers for dynamic enum, but accept answer is not to do it


否。枚举始终在编译时固定。您执行此操作的唯一方法是动态生成相关的字节码。

No. Enums are always fixed at compile-time. The only way you could do this would be to dyamically generate the relevant bytecode.

从数据库(例如ID)中查找值(主要是ID)的更好的解决方案是什么? 30)

What will be a better solution for finding also values (mainly IDs) from database (for example ID 30)

 select ID from TYPE

$ b中选择ID
$ b

我可以扩展现有状态,而不是更改它吗?可以使用方法从数据库添加额外的IDS吗?

Can I extends existing state instead of change it? can I add extra IDS from database using method?

编辑

即使我更新为@StefanFischer提出了一个用enum类和新数据库类填充映射的接口,我仍然希望在代码中使用 byId 方法

Even if I update as @StefanFischer suggested an interface which populate map with enum class and new database class, I still expect in code an enum return by byId method,

public interface MyType {
    public static class Holder {
        static Map<Integer, MyType> idMap = new HashMap<>();
        private Holder() { }
    }

    public default void add(MyType myType, Integer id) {
        Holder.idMap.put(id, myType);
    }


    public static MyType byId(Integer id) {
        return Holder.idMap.get(id);
    }
}


推荐答案

如果我对它的理解是正确的,要求是:

If I understand it correctly the requirements are:


  • 具有一个MyType.byId(Integer id)方法,该方法可以提供一些预定义的值

  • 它还应该从数据库的表 Type 中动态扩展

  • having a MyType.byId(Integer id) method that delivers some predefined values
  • it should be also extended dynamically from a Table Type from the database

因此不能动态扩展枚举,但是我们可以切换到一个类。

So a enum can not be extended dynamically, but we could switch to a class.

因此,紧贴您的代码,可能会写出以下内容:

So staying close to your code one could write something like:

import java.util.HashMap;
import java.util.Map;

public class MyType {

    static Map<Integer, MyType> idMap = new HashMap<>();
    static {
        idMap.put(10, new MyType("First Type"));
        idMap.put(20, new MyType("Second Type"));
    }

    private final String name;

    private MyType(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public static MyType byId(Integer id) {
        return idMap.get(id);
    }

    public static void addType(String name, Integer id) {
        MyType lookup = byId(id);
        if(lookup != null) {
            if(!lookup.getName().equals(name)) {
                System.out.println("conflicting redefinition for id " + id + ": '" + name + "' vs '" + lookup.name + "'");
                //handle...
            }
        }
        idMap.put(id, new MyType(name));
    }
}

测试数据

假设我们在数据库中有以下内容:

Let's assume we have the following in the database:

stephan=# select * from Type;
 id |    name     
----+-------------
 30 | Third Type
 10 | First Type
 20 | Second Type
(3 rows)

因此在数据库中,我们具有ID为的预定义类型= 10和id = 20,但是id = 30的类型在应用程序默认情况下是未知的。但是我们可以从数据库中填充类型。

So in the database we have the predefined types with id=10 and id=20 but also a type with id=30 that is not known per default to the application. But we can populate the types from the database.

测试用例

public static void main(String[] args) {
    try {
        Connection connection = createConnection();
        try (connection) {
            populateTypes(connection);
        }

        MyType type;

        type = MyType.byId(10);
        System.out.println(type.getName());

        type = MyType.byId(20);
        System.out.println(type.getName());

        type = MyType.byId(30);
        System.out.println(type.getName());

    } catch (Exception e) {
        e.printStackTrace();
    }
}

JDBC示例

使用哪种实际数据库技术检索值都没有关系。下面是JDBC的示例:

It doesn't matter what actual database technology is used to retrieve the values. Here an example for JDBC:

private static void populateTypes(Connection connection)
        throws SQLException {

    String sql = "SELECT * FROM type";
    try (Statement st = connection.createStatement()) {
        try (ResultSet rs = st.executeQuery(sql)) {
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                MyType.addType(name, id);
            }
        }
    }
}

演示输出

First Type
Second Type
Third Type

您正在寻找什么?

这篇关于枚举数据库中的常量和动态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆