Populate an enum with values from database

2020-02-08 07:21发布

I have a table which maps String->Integer.

Rather than create an enum statically, I want to populate the enum with values from a database. Is this possible ?

So, rather than delcaring this statically:

public enum Size { SMALL(0), MEDIUM(1), LARGE(2), SUPERSIZE(3) };

I want to create this enum dynamically since the numbers {0,1,2,3} are basically random (because they are autogenerated by the database's AUTOINCREMENT column).

6条回答
劳资没心,怎么记你
2楼-- · 2020-02-08 07:45

This is a bit tricky, since the population of those values happens at class-load time. So you will need a static access to a database connection.

As much as I value his answers, I think Jon Skeet may be wrong this time.

Take a look at this:

public enum DbEnum {
    FIRST(getFromDb("FIRST")), SECOND(getFromDb("second"));

    private static int getFromDb(String s) {
        PreparedStatement statement = null;
        ResultSet rs = null;
        try {
            Connection c = ConnectionFactory.getInstance().getConnection();
            statement = c.prepareStatement("select id from Test where name=?");
            statement.setString(1, s);
            rs = statement.executeQuery();
            return rs.getInt(1);

        }
        catch (SQLException e) {
           throw new RuntimeException("error loading enum value for "+s,e);
        }
        finally {
            try {
                rs.close();
                statement.close();
            } catch (SQLException e) {
                //ignore
            }
        }
        throw new IllegalStateException("have no database");
    }

    final int value;

    DbEnum(int value) {
        this.value = value;
    }
}
查看更多
男人必须洒脱
3楼-- · 2020-02-08 07:45

You need to replicate in code what is in the database (or vice-versa). See this question for some good advices.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-08 07:53

In all the languages I know enums are static. The compiler can make some optimizations on them. Therefore the short answer is no, you can't.

The question is why you want to use an enum in this way. What do you expect? Or in other words why not use a collection instead?

查看更多
戒情不戒烟
5楼-- · 2020-02-08 07:54

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

Having said that, you should probably work out which aspects of an enum you're actually interested in. Presumably you weren't wanting to use a switch statement over them, as that would mean static code and you don't know the values statically... likewise any other references in the code.

If you really just want a map from String to Integer, you can just use a Map<String, Integer> which you populate at execution time, and you're done. If you want the EnumSet features, they would be somewhat trickier to reproduce with the same efficiency, but it may be feasible with some effort.

So, before going any further in terms of thinking about implementation, I suggest you work out what your real requirements are.

(EDIT: I've been assuming that this enum is fully dynamic, i.e. that you don't know the names or even how many values there are. If the set of names is fixed and you only need to fetch the ID from the database, that's a very different matter - see Andreas' answer.)

查看更多
混吃等死
6楼-- · 2020-02-08 08:02

Improving on what Andreas did, you can load the contents of the database into a map to reduce the number of database connections needed.

public enum DbEnum {
    FIRST(getFromDb("FIRST")),
    SECOND(getFromDb("second"));

    private Map<String,Integer> map;
    private static int getFromDB(String s)
    {
        if (map == null)
        {
           map = new HashMap<String,Integer>();
           // Continue with database code but get everything and
           // then populate the map with key-value pairs.
           return map.get(s);
        }
        else {
            return map.get(s); }
    }
}
查看更多
干净又极端
7楼-- · 2020-02-08 08:11

Enums are not dynamic, so the short answer is that you can't do it.

Also have a look at Stack Overflow question Dynamic enum in C#.

查看更多
登录 后发表回答