【问题标题】:JPA @MappedSuperclass different Id counters for subclassesJPA @MappedSuperclass 子类的不同 Id 计数器
【发布时间】:2015-05-26 08:02:43
【问题描述】:

我有一个@MappedSuperclass,它是我所有实体的基类(@Entity,通过多个子类直接或间接)。

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@XmlAttribute(required = true)
private Long primaryKey;

Id 的生成如上所示。

我的问题是每个@Entity 的@Id 计数器都是相同的。事实上,这不是一个大问题,因为它需要一段时间才能达到 Long.MAX_VALUE。但是达到最大值要容易得多,因为所有实体只有一个计数器。如何使用不同的@Id-counter 而无需将上述代码添加到所有@Entity-classes?

(如果您的回答很重要:我使用的是 H2 数据库。)

【问题讨论】:

标签: java jpa mappedsuperclass


【解决方案1】:

如果您的数据库和表支持AUTO_INCREMENT,请将注释更改为此@Id @GeneratedValue(strategy=GenerationType.IDENTITY)。然后在提交时会生成id。

通过 TABLE 或 SEQUENCE 策略还有另一种方法,但它需要根据 Entity 显式定义,这对于抽象 BaseEntity 来说是个问题。看看吧:

@Entity
@TableGenerator(name="tab", initialValue=0, allocationSize=50)
public class EntityWithTableId {
    @GeneratedValue(strategy=GenerationType.TABLE, generator="tab")
    @Id long id;
}

编辑: 嗯,所以这是可能的! MappedSuperclass - Change SequenceGenerator in Subclass

【讨论】:

    【解决方案2】:
    @Id
    @Column(name = "ID", unique = true, nullable = false)
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "SEQ_AAAAAAAAAAA")
    @TableGenerator(
    name = "SEQ_AAAAAAAAAAA", 
    table = "SEQ_ENTITY" /*<<<==YOUR TABLE NAME FOR SAVE NEXT VALUES HERE*/, 
    pkColumnName = "ENTITY", 
    initialValue = 1, 
    valueColumnName = "NEXT_ID", 
    pkColumnValue = "packageee.PACK.PAK.YOURCLASSNAME",     
    allocationSize = 1)
    private Long id;
    

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      相关资源
      最近更新 更多