在 MySQL 和 Hibernate 中使用序列
我正在开发一个使用 Hibernate 和 MySQL 的项目。我打算使用序列为数据库中的所有表生成 ID。 (很难描述我的问题,所以我将向您展示一个例子)。
例如:我有 2 个表 A & B. 首先,我向表 A 插入 10 条记录,它们的 ID 为 1 到 10。然后,我向表 B 插入 10 条记录,并且我希望它们的 ID 为 11-20,而不是 1-10。这意味着生成的ID值将按数据库中所有表中的所有记录进行统计,而不是单个表中。
那么如何在 MySQL 中使用这个概念呢?声明和语法? 在 Hibernate 中,如何在数据模型上使用策略和生成器来在数据库中应用生成的策略? 太感谢了!
I'm working on a project that uses Hibernate and MySQL. I intend to use sequence to generate ID for all tables in database. (It's hard to describe my question, so I will show you as an example).
For example: I have 2 tables A & B. Firstly, I insert 10 records to table A, and their IDs will be 1 to 10. Then, I insert 10 records to table B, and I want their IDs will be 11-20, not 1-10. It means the generated ID value will be counted by all records in all tables in databases, not in a single table.
So how can I use that concept in MySQL? Declare and syntax?
In Hibernate, how can I use the strategy and generator on data model to apply that generated strategy in database?
Thank you so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在 Mysql 中没有序列,但可以使用“TABLE”id 生成
您可能需要在所有实体中添加代码段
@javax.persistence.TableGenerator [...]
编辑
不幸的是,我不知道一个优雅的方法来做到这一点:(。在我的项目中,我们在多个实体中使用 a 序列,并且我们需要在每个类中声明该序列。
您可以尝试的一件事(但我不太喜欢)是为所有实体创建一个超类,并且该超类仅包含 ID 字段和注释。我有一种感觉,我在一个项目中看到过这个,但我不是 100% 确定。
关于告诉数据库使用该策略,我认为这是不可能的。您可以尝试添加触发器并将其应用到架构中的每个表。当您在表中插入新行、从生成器表中选择一个值并将其添加到该行时,触发器将触发。老实说,我不知道这是否可行,而且我 99% 确信如果您有 2 个并发会话创建行,这将不起作用。
您能否重新考虑您的策略并为 ids 使用正常的自动增量列并将序列号放入表的另一列中?
You don't have sequences in Mysql, but you can use the 'TABLE' id generation
You might need to add the snippet
@javax.persistence.TableGenerator [...]
in all your entitiesEdit
Unfortunately, I don't know an elegant way to do this :(. In my project, we use the a sequence in several entities, and we need to declare the sequence in each class.
One thing you could try (but I don't really like) is to create a super class for all of your entities, and that superclass only contains the ID field and the annotations. I have the feeling that I've seen this in a project, but I'm not 100% sure.
About telling the DB to use that strategy, I don't think it's really possible. You can try to add a trigger and apply it to each table in the schema. The trigger will fire when you insert a new row in the table, pick a value from the generator table, and add it to the row. I honestly don't know if this might work, and I'm 99% sure that this won't work if you have 2 concurrent sessions creating rows.
Can you rethink your strategy and use normal auto-increment columns for the ids and put the sequential number in another column of your tables?