错误:无法使用身份列键生成<union-subclass>(TABLE_PER_CLASS)

问题描述 投票:0回答:1

我正在使用 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.子类:

@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 主列生成的自动增量值的解决方案。

提前感谢大家。

P.S.:我已经浏览过以下帖子: 无法使用 ( TABLE_PER_CLASS )

生成标识列键
mysql spring hibernate hibernate-mapping class-table-inheritance
1个回答
0
投票

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

我遇到了同样的问题,我通过将 @GenerateValue(strategy = GenerationType.TABLE) 替换为 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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.