我使用 Eclipselink 作为我的 JPA 提供程序,我如何使字段自动递增?
最佳答案
I just want an auto-increment field for 1 entity.
是的,我明白了,这就是您在问题中所写的内容。但它可以有多种解释方式,重复同样的事情而不加澄清也无济于事:)
So does Pascal's way work or I have to do what Bytecode suggest, query select (max) counter + 1 from MyEntity, to get the next value, then set it to the design field, the persist?
如果您想为每个实体记录增加一个字段(例如,id=1 的Order
的“计数器”,Order
的另一个“计数器” > with id=2),我的建议是可行的。
如果您想要类似于主键的行为(即自动递增的列),它不会。在这种情况下,标准 JPA 不提供任何特定设施(标准 JPA 仅允许 GenereatedValue
在 Id
注释字段上)。我能想到的唯一方法是插入另一个专用实体以从中获取主键。
您的确切要求尚不清楚,但我假设您是在谈论随机字段,而不是主键。在这种情况下,您可以使用生命周期回调方法:
@Entity
public class MyEntity {
...
private int counter;
...
@PrePersist
@PreUpdate
protected void increment() {
counter = counter + 1;
}
}
关于JPA:如何使字段自动递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3832739/