4

我正在使用 Hibernate 来保存所有实体都继承自基本抽象实体的实体。对于所有具体实体,分别有数据库表,具有自动增量主键列。但是使用 GenerationType 作为“AUTO”或“IDENTITY”会出错。我希望代表每个具体实体类的数据库表中的所有记录都应该具有顺序递增的 ID 值。

com.something.SuperClass:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class SuperClass implements Serializable {
    private static final long serialVersionUID = -695503064509648117L;

    long confirmationCode;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO) // Causes exception!!!
    public long getConfirmationCode() {
        return confirmationCode;
    }

    public void setConfirmationCode(long confirmationCode) {
        this.confirmationCode = confirmationCode;
    }
}

com.something.SubClass:

@Entity
public abstract class Subclass extends SuperClass {
    private static final long serialVersionUID = 8623159397061057722L;

    String name;

    @Column(nullable = false)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

给了我这个例外:

Caused by: org.hibernate.MappingException: Cannot use identity column key
generation with <union-subclass> mapping for: com.something.SuperClass
What's the best and most convenient way for me to generate the ID's? I do not want to change my inheritance strategy.

我知道如果我将 GenerationType 从“AUTO”更改为“TABLE”可以解决这个问题,但是这个解决方案的问题是,生成的密钥的顺序不准确。它在键之间留下了很大的间隙。

我正在寻找允许所有表使用由 Mysql AutoIncrement 主列生成的 Auto Incremental 值的解决方案。

在此先感谢大家。

PS:我已经浏览过以下帖子: Cannot use identity column key generation with <union-subclass> (TABLE_PER_CLASS)

4

1 回答 1

0

这里的问题是你混合了“每个类的表”继承和 GenerationType.Auto。在“每类表”策略中,每个类使用一个表,每个表都有一个 ID。

我有同样的问题,我通过用 GenerationType.TABLE 替换 @GeneratedValue(strategy = GenerationType.TABLE) 来解决这个问题

最终代码如下所示

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class SuperClass implements Serializable {
    private static final long serialVersionUID = -695503064509648117L;

    long confirmationCode;

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    public long getConfirmationCode() {
        return confirmationCode;
    }

    public void setConfirmationCode(long confirmationCode) {
        this.confirmationCode = confirmationCode;
    }
}
于 2021-11-15T08:09:43.900 回答