英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论