[英]What is the correct way to use db values in code
我在代碼中進行了很多地方的硬編碼比較,對此我並不滿意。 我正在尋找解決此問題的正確方法。
例
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
是表statuses
精確副本,並且是return this.stage.getId() == Status.ENDED;
statuses
精確副本return this.stage.getId() == Status.ENDED;
線。 現在,如果任何時候值都將更改( id
/ name
),我也必須更改static int
。 我看不到如何更改它,但是如果您知道一種方法,請分享。
有幾種方法。 這可以是其中之一:
final
關鍵字。 用Java反射填充常量中的值。
Field field = Status.class.getDeclaredField(name); field.setInt(field, id);
您仍然必須將這些值硬編碼在數據庫中或代碼中的某個位置,因為否則,您將根本不知道每個值代表什么。 之后,您可以根據需要將它們持久保存到數據庫中,也可以加載到應用程序中。
如Paul所寫,您將在應用程序啟動時從DB加載值,但我建議使用enum
而不是許多int
常量,這樣可以省去很多麻煩。
這是一個您可能會發現有用的鏈接,關於常量的枚舉,請閱讀J.Bloch,Effective Java。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.