我有一个实体对象,代表一个由4个玩家组成的游戏,每个游戏玩家坐在他们的桌子一侧, N , E , S 或 W 。游戏以如下方式存储在数据库中:
CREATE TABLE game_slot (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
...
player_N VARCHAR(127) NOT NULL,
player_E VARCHAR(127) NOT NULL,
player_S VARCHAR(127) NOT NULL,
player_W VARCHAR(127) NOT NULL,
...
);
每列声明为 NOT NULL -始终有4位玩家。
但是,我希望GameSlot
对象具有一个players
对象,而不是4个普通字段。该字段仅包含具有4个条目的映射。
public class GameSlot {
private int id;
private Map<String, String> players = new HashMap<>();
...
}
当前,我通过为每个映射表列添加委派虚拟属性来实现此目的:
...
@JsonIgnore public String getPlayerN() { return this.players.get("N"); }
@JsonIgnore public String getPlayerE() { return this.players.get("E"); }
@JsonIgnore public String getPlayerS() { return this.players.get("S"); }
@JsonIgnore public String getPlayerW() { return this.players.get("W"); }
public void setPlayerN(String value) { this.players.put("N", value); }
public void setPlayerE(String value) { this.players.put("E", value); }
public void setPlayerS(String value) { this.players.put("S", value); }
public void setPlayerW(String value) { this.players.put("W", value); }
...
使用xml映射很简单:
<!-- GameSlot.hbm.xml -->
...
<property name="playerN" column="player_N" not-null="true" length="127" />
<property name="playerE" column="player_E" not-null="true" length="127" />
<property name="playerS" column="player_S" not-null="true" length="127" />
<property name="playerW" column="player_W" not-null="true" length="127" />
...
但是,这种方法似乎很尴尬,我想找到更好的解决方案。因此,如何将多个表列映射到单个映射中?一些正在发生的情况:
String
| varchar(127)