Persisting time ojects as entities instead of valu

2019-07-28 02:02发布

问题:

I'm using Joda Time DateTime to handle date and time. I persist objects of this kind using the class PersistentDateTime bundled in the jodatime hibernate code.

I have large collections of DateTime objects, and I currently persist them in the following way (an excerpt of an hibernate mapping file follows):

<set name="validInstants" sort="natural">
     <key column="myobject_id"/>
     <element column="date" type="myproject.utilities.hibernate.types.PersistentDateTime"/>
 </set>

Doing so, i.e. storing DateTimes as value types, I get many duplicate elements in the table validInstants, hundreds of thousands of them. I'd like to avoid this and have in the validInstants table the DateTimes needed, stored once per value. How can I achieve this?

As far as I know (I'm and Hibernate beginner) the only way to achieve this is by creating a class that wraps a DateTime and maps it as an entity, plus creating a factory which returns always the same DateTime-wrapper when asking for the same Date. Is this the best way to do what I want? Suggestions?

回答1:

What exactly is the relationship between the entity being stored here and the validInstants set? Does the entity "own" the validInstants? Does a member of validInstants have any use or life outside of the entity it is declared as a part of?

If not, then I don't think it makes any sense to treat a non-entity as an entity (which would be what you'd be doing if you "creating a class that wraps a DateTime and maps it as an entity").

I would not worry about having many duplicate elements in the table storing these dates, unless it's proven to be a large problem. With indexing on the myobject_id column, these lookups should be fast enough.