How to Map Lookup Tables in Hibernate for Semi-Static data
I'm dealing with an existing table of events:
Event Table:
id event_type status ...
== ========== ======
1 high.temperature ACCEPTED
2 missing.invoice WAITING
3 missing.invoice WAITING
Currently there are a few hundred even开发者_StackOverflowt_types and five status. This table has millions of rows, and I would like reduces its size by using lookup tables for event_type and status. status is fine, since it has a small number of static values, but event_type is controlled by external systems and events are sometimes received by my system with new values that will have to be added to the lookup tables.
I believe the existing table structure was chosen to make mapping with hibernate easy, which it does quite well, but results in a lot of redundancy.
What I want is something like this:
Event Table:
id event_type status ...
== ========== ======
1 223 3
2 245 4
3 245 4
EventType Table:
event_type name
========== ================
223 high.temperature
245 missing.invoice
My question is, is there any way to automate inserts and selects to/from the lookup table, so that I don't have have to define a Java class for EventType and and lookup the appropriate EventType every time I insert into Event? On the java side, I would prefer to treat the event_type as a plain String, as it is now.
Read operations shouldn't cause any problem : create an EventType
entity, add a private eagerly-fetched many-to-one relationship between Event
and EventType
, put EventType
in the second-level cache, and add a getter returning the event type's name in Event
. This makes it transparent to the rest of the application, and doesn't cause additional selects thanks to the second-level cache.
Insertion is harder, though, because you probably don't want to make your entities access the session to make new event types persistent. And even if this it was acceptable, I guess you'd want to have a unique constraint for the event type name, which could make some event creations fail if two events with the same new event type are created in parallel.
I would create a service which would "get or create" an event type based on a name. This service would use a dedicated transaction to create the event type in order to reduce the probability of conflicts. And I would use this service each time I need to assign an event type to an event (which, I guess, should be much less frequent than reading an event's type).
精彩评论