我希望能够在 hibernate 中使用我自己的自定义 id 生成器,但又不会每个实体都有多个注释带来的困惑。
示例:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
@GenericGenerator(name = "XyzIdGenerator",
strategy = "com.mycompany.myapp.id.BigIntegerSequenceGenerator",
parameters = {
@Parameter(name = "sequence", value = "xyz_id_sequence")
})
这已经很多了。我想将其设置在 hibernate 状态看到“@Id”的位置 默认情况下,它会调用我的生成器并将其分配给 id。
最佳答案
我通常这样做的方法是创建一个父类(super class),其中包含共享的带注释的变量并使实体扩展它。示例:
@MappedSuperclass
public class PersistableEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
@GenericGenerator(name = "XyzIdGenerator",
strategy = "com.mycompany.myapp.id.BigIntegerSequenceGenerator",
parameters = {
@Parameter(name = "sequence", value = "xyz_id_sequence")
})
protected Long id;
// ...
}
@Entity
public class Abc extends PersistableEntity {}
@MappedSuperclass
在这里很重要:
Designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.
关于java - 默认情况下如何在 hibernate 中使用自定义 key 生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367538/