使用 @TableGenerator 为相关实体提供可扩展的顺序 ID 生成器
我正在编写一个 Web 应用程序,其中一些 ID 对 URL 中的用户可见。该应用程序旨在供更多拥有每个帐户的用户使用。一个帐户可以有项目,每个项目都有任务。
现在,我不希望用户使用 ID 24876(或任何正常生成的 ID)创建他们的第一个项目,而是希望有一个“好看的”顺序标识符另外生成的主键(主要是因为操作具有非复合标识符的实体更简单)。我们将这些顺序 ID 称为 viewIds。
对于每个不同的“父”标识符(对于项目,这将是一个帐户),ViewID 将从 1 开始。组合(accountId,projectViewId)是唯一的,以及(projectId,taskViewId)等。
我的问题是:如何生成这些viewId?我正在考虑也许使用 TableGenerator 机制,但是这个机制也可以用于非标识符列吗?
但最重要的是,在多个应用程序服务器使用相同数据库的环境中生成此类 ID 的最佳方法是什么(理想情况下不需要让它们直接相互通信)?是否已经有 TableGenerator 的实现或实现上述功能的实用程序?
I am writing a web-application where some IDs will be visible to the users in the URL. The application is meant to be used by more users having each an Account. An Account can then have Projects, and each Project has Tasks.
Now, I do not want the users to have their first project created with an ID of 24876 (or whatever a normal generated ID would be), but rather to have a "nice looking" sequential identifier additionally to a generated primary key (mainly because it is simpler to manipulate entities that have non-composite identifiers). Let's call these sequential IDs viewIds.
ViewIDs would start at 1 for each different "parent" identifier (for a Project, that would be an Account). The combination (accountId, projectViewId) is unique, as well as (projectId, taskViewId) etc.
My question is: how to generate these viewIds? I was thinking of perhaps using the TableGenerator mechanism, but can this one also be used for non-identifier columns?
Most importantly though, what would be the best way to generate such IDs in an environment where several application servers use the same database (and ideally without the need to have them communicate with eachother directly)? Is there perhaps already an implementation of a TableGenerator or a utility that achieves the above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,这就是我最终采用的解决方案:
我没有依赖 Hibernate/JPA 来管理这些“漂亮”的 ID,而是选择了基于数据库的方法:
我不确定的一件事是,这在数据库的主到主复制中会如何表现,其中两个数据库服务器都可以使用。但对于应用程序服务器复制来说,这应该可以完成工作。
Allright, this is the solution I ended up adopting:
instead of relying on Hibernate/JPA to manage these "nice looking" IDs, I chose a database-based approach:
The one thing I am not sure about is how this would behave in e.g. a master-to-master replication of the database, where both database servers can be used. But for application server replication, this should do the job.