christian wrote:
The constraint for a many-to-one is called "foreign key". Everything else wouldn't be a many-to-one.
I would agree with this statement, however having the ability to append arbitrary sql to all queries (including association and primary key queries) would still be useful as a mechanism for creating "dynamic views" on audit history tables.
The ability not just to save audit history but also to load historical versions into domain objects is a comon requirement in the world of derivatives trading systems. Every system I know of that has solved this problem uses a proprietary ORM layer, since standard solutions do not exist.
Although with Hibernate it is possible to use views and triggers to save audit history, as far as I am aware there is no way to load a version as of a particular date in history. However I believe it should be possible with some modifications.
The assumption is that the entities being versioned have both Version and LastUpdated properties, and that two parallel sets of tables exist in the database (one holding the latest version of each entity, and one holding all versions). The history tables are maintained via triggers on the primary tables.
To query on the history tables, the user would create a new SessionFactory with the desired as-of date. When configuring this factory each versioned entity is mapped to its history table, with some additional filter sql to select the last version as-of the specified date.
So if a normal query looks like:
select <...> from Foo f where f.Id=42
the corresponding history query would look like:
select <...> from Foo_history f where f.Id=42 inner join
(select Id, max(Version) as Version from Foo_history
where LastUpdated<='12/31/2004' group by Id) as fh
on f.Id=fh.Id and f.Version=fh.Version
It seems to me that anytime you step into the world of audit history, you end up going outside the bounds of strict relational algebra. However, in the real world (if financial derivatives can be considered the real world) the ability to extend the ORM mappings to audit history is an important requirement.