关系数据库中不包含唯一标识符的映射对象字段

Mapping Object fields that do not contain a unique identifier in a relational database

我有一个 Reward 类型的对象,它是 Card class 中的一个字段。我正在尝试将 Card class 存储在数据库中。 Card 中的其他字段对于数据库持久性不是问题,因此为简洁起见,我们将只关注 Card 中的 Reward 字段。

这是奖励class。为简洁起见,getters/setters 已被删除。

public class Reward {
private RewardType rewardType;
//Value should be 1 for weapons
private int amount;
//Null unless RewardType is weapon
private WeaponData weaponData;

public Reward() {
}

public Reward(RewardType rewardType, int amount) {
    if (rewardType == RewardType.WEAPON) {
        throw new IllegalArgumentException("A weapon must contain a non-null WeaponData field");
    }
    this.rewardType = rewardType;
    this.amount = amount;
}

public static class WeaponData {
    private int attack;
    private int durability;

    public WeaponData(int attack, int durability) {
        this.attack = attack;
        this.durability = durability;
    }

    public int getAttack() {
        return attack;
    }

    public void setAttack(int attack) {
        this.attack = attack;
    }

    public int getDurability() {
        return durability;
    }

    public void setDurability(int durability) {
        this.durability = durability;
    }
}

}

我在尝试将驻留在 Card class 中的对象映射到数据库时遇到的问题是,Reward 不是天然的唯一实体,因此它不包含 id。它只是一组已捆绑到单个 class.

中的 Card 属性

到目前为止我想出的唯一解决方案是数据库中没有 Reward 的外键,而是将所有 Reward 字段非规范化以放置在 Cards table.

例如,卡片 table 将包含 reward_type、金额和 weapon_data 列,而不是奖励的外键。

我问过我的朋友这个方法,他们提到它是非规范化的,所以这不是一个优雅的解决方案。

我在使用名为 Sql2o 的瘦 JDBC 包装器进行映射时也会遇到问题,因为它无法帮助我顺利地将对象映射到数据库 table。

我考虑过将我的数据库 table 的 一些 切换到 NoSql 数据库,这将使这种情况变得容易得多,因为对象很容易映射到 JSON 文档并存储在数据库中。

但是,它确实带来了一些大问题,因为我数据库中的其他 table 包含对卡片 table.

的外键引用

如果有人有解决方案以干净的方式将这些 Reward 对象映射到数据库,我们将不胜感激。

感谢您阅读本文。

我使用 Hibernate ORM 解决了这个问题。将字段标记为 @Embedded 并将其类型标记为 @Embeddable 解决了这个问题。

似乎解决方案是将不包含标识符的字段简单地放置在 table 或 embed 中。

对于集合,这更复杂,需要生成伪 ID 以持久保存实体,但这是另一个主题。