简体   繁体   中英

Generating primary key that is unique across multiple tables

I am working on a restaurant app using Hibernate. I have several entities like Pizza, Beverage, Pasta etc.

I want these to be persisted to different tables but have primary keys that are unique among all. ie if I say itemId 4 it should be sufficient to identify any of the food items available.

Any idea how to do it guys?

I would prefer a solution using Hibernate annotations. :-|

您可以使用db序列,然后您的任何实体都可以使用此序列来生成其ID。

An UUID would be unique for all tables, but you won't be able determine which the table is based on the id only.

To be honest, this is a bit strange requirement. But if you really insist on it, you can simply prefix the table/entity name to the primary key. For that you'd need a custom generator. See this question .

You can use inheritance. Have a base entity @MappedSuperclass Item , with @Inheritance strategy set to table-per-class and then Pasta , Pizza . If the fields don't differ much you use even single-table strategy with a discriminator column. And if your entity types are likely to grow, you can simply have one Item with a column type

I think you have not got the analysis quite correct. If you look how you will use thee entities you mention I think there will also be an entity like order that will contain several of these, also all these entities do have some similarity they all can be considered a subclass of 'menu item' as they all have some common attributes eg price and can be used in the same way eg included in an order.

You can look at section 5.1.6 in Hibernate core documentation as to how to implement various strategies of mapping the OO modle to a table or several tables. Note that Table per class strategy and 10.1.5. Table per concrete class would give you your current table setup but you need to be able to generate the key which you sat MySQL cannot do easily. However I think you will find that there are common properties that should be on the base class and so another form of the mapping would be needed and you end up with a menu item table and that can easily have a generated id.

I agree with Mark, it seems something like a table per subclass would fit your design and needs to have an id across multiple items. Also note that having your items in multiple table without a common parent table could lead to some trouble when you are in the need of a FK for these items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM