代码之家  ›  专栏  ›  技术社区  ›  Vasily Liaskovsky

Hibernate:将列映射到固定大小的映射

  •  1
  • Vasily Liaskovsky  · 技术社区  · 6 年前

    我有一个实体对象,代表一个游戏,每个玩家坐在他们的桌边,其中一个 N个 , E类 , S公司 西 . 游戏存储在数据库中,如下所示:

    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,
      ...
    );
    

    每列都被声明 不为空 -总有四个人。

    但是,我想要的不是4个简单的字段 GameSlot 反对单身 players 包含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" />
      ...
    

    然而,这种方法似乎很尴尬,我想找到更好的解决方案。所以, 如何将多个表列映射到单个映射 ? 一些正在发挥作用的条件:

    1. 受影响的列的数量是固定的,总是4列
    2. 每一列都是 不为空
    3. 属性|列类型都相同- String | varchar(127)
    4. 要使用的键是已知的、固定的和所有相同类型的
    5. 我宁愿使用xml映射,但注释也可以。
    0 回复  |  直到 6 年前