JPA标准是否提供了一种机制,允许开发人员编写ID生成器?

huangapple go评论63阅读模式
英文:

Does the JPA standard provide a mechanism to allow developers to write an ID generator?

问题

Hibernate支持自定义ID生成器,如https://stackoverflow.com/questions/47259048/how-to-generate-custom-id-in-jpa中所述。

我想知道是否有JPA标准的方法来实现这个?

英文:

Hibernate supports a custom ID generator as noted in https://stackoverflow.com/questions/47259048/how-to-generate-custom-id-in-jpa

I was wondering, is there a JPA standard way of doing it?

答案1

得分: 2

不过,你可以编写自己的逻辑,在PrePersist生命周期回调方法中分配主键。

这可以进一步扩展为使用EntityListener,如https://stackoverflow.com/a/54006736/242042中所述,允许你注入Spring管理的bean,如果EntityListener由Spring管理,则可能需要这些bean。

如果EntityListener不由Spring管理,ThreadLocal可能是一个备选方案(参考:https://stackoverflow.com/questions/63321914/is-it-safe-to-pass-in-the-spring-application-context-into-a-threadlocal-associat?noredirect=1#comment111971158_63321914)。

英文:

No, but you can write your own logic to assign primary key in a PrePersist lifecycle callback method.

This can further be expanded to use an EntityListener as noted in https://stackoverflow.com/a/54006736/242042 which allows you to inject Spring managed beans that your PrePersist operation would require if the EntityListener is managed by Spring.

If the EntityListener is not managed by Spring, ThreadLocal may be an alternative (rel: https://stackoverflow.com/questions/63321914/is-it-safe-to-pass-in-the-spring-application-context-into-a-threadlocal-associat?noredirect=1#comment111971158_63321914)

huangapple
  • 本文由 发表于 2020年8月8日 03:20:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63308008.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定