【问题标题】:What is the correct way to use db values in code在代码中使用 db 值的正确方法是什么
【发布时间】:2013-08-12 18:31:52
【问题描述】:

我在代码中的很多地方都进行了硬编码比较,我对此并不满意。我正在寻找解决此问题的正确方法。

示例

public class Status {
  public static final int ACTIVE = 1,
                        INACTIVE = 2,
                           ENDED = 3,
                          PAUSED = 4,
                             NEW = 5,
                            INIT = 6,
                         STARTED = 7;

  private int id;
  private String name;

  public int getId(){ return this.id; }
  public String getName(){ return this.name; }

  //get and set the object from the db by the id
  public Status(int id){}
}

public class Job {
  private int id;
  private Status stage;

  //get and set the object from the db by the id
  Job(int id){}

  public boolean isStageStatusEnded(){
    return this.stage.getId() == Status.ENDED;
  }
}

我有这个数据库表:

mysql> desc statuses;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20) | NO   |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

mysql> select * from statuses;
+----+----------+
| id | name     |
+----+----------+
|  1 | ACTIVE   |
|  2 | INACTIVE |
|  3 | ENDED    |
|  4 | PAUSED   |
|  5 | NEW      |
|  6 | INIT     |
|  7 | STARTED  |
+----+----------+

如您所见,Status 类中的static final int 是表statusesreturn this.stage.getId() == Status.ENDED; 行的精确副本。现在,如果在任何时候值会改变(id/name),我也必须改变static int。我不知道我该如何改变它,但如果你知道一种方法 - 分享它。

【问题讨论】:

    标签: java database database-design constants


    【解决方案1】:

    有几种方法。这可以是其中之一:

    1. 从常量中删除 final 关键字。
    2. 启动应用程序时,向数据库查询当前值。
    3. 使用 Java 反射填充常量中的值。

      Field field = Status.class.getDeclaredField(name);
      field.setInt(field, id);
      

    【讨论】:

      【解决方案2】:

      您仍然必须将这些值硬编码在某个地方,无论是在数据库中还是在代码中,否则您将根本不知道每个值代表什么。之后,如果适合您的需要,您可以将它们保存到数据库中,也可以加载到您的应用中。

      正如 Paul 所写,您会在应用程序启动时从 DB 加载值,但我建议使用 enum 而不是多个 int 常量,这可能会节省很多精力。

      Here 是一个您可能会发现有用的链接,关于常量上的枚举,请阅读 J.Bloch,Effective Java。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-08
        • 2012-11-30
        • 2010-11-22
        • 1970-01-01
        • 2022-08-17
        相关资源
        最近更新 更多