3

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

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

Id 的生成如上所示。

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

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

4

2 回答 2

1

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

通过 TABLE 或 SEQUENCE 策略还有另一种方法,但需要根据Entityabstract 的问题来明确定义BaseEntity。看看:

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

编辑:嗯,这是可能的! MappedSuperclass - 在子类中更改 SequenceGenerator

于 2015-05-26T08:12:53.480 回答
0
@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;
于 2018-02-16T22:28:12.133 回答