views:

89

answers:

3

Is there a way to "magically" persist a column which is not represented as a property in an entity? Concretely I want to add audit info to an entity without having the audit info on the entity. The audit values are not stored in the entity, but are retrieved from the environment at the time of persisting the entity. This happens in a AuditInfoUserType. The nullSafeSet gets the info from the SecurityContext, instead of reading from the entity.

In the hibernate mapping, however, the audit info properties have to be defined.

Is there a way in hibernate to define columns without properties?

A: 

I would specify the audit info mapping as a component of the actual entity, e.g.:

<class name="EntityName" table="TABLE_NAME">

        <property name="name" column="NAME" not-null="true"/>

        <component name="auditInfo">
            <property name="ipAddress" column="IP_ADDRESS"/>
        </component>        
</class>

But obviously for that you would need to create a field auditInfo in the EntityName class to hold the audit info when it's ready to be set.

If you really don't want to include the auditInfo in the class, I guess you will need to save it with a SQL.

Bruno Rothgiesser
Is there a way to modify the hibernate generated sql at the time of saving?
lewap
+1  A: 

There is an onPreparedStatement() method on the interceptor API that could be used to mess with Hibernate's SQL. That seems like a lot of risk to me, just to avoid having a private field with no accessors lurking on your Entity object. Executing a separate SQL inside a listener is probably much more robust than trying to manually munge hibernate's statements. Just the parsing to figure out what it's used as the alias name for your entity table would be ugly, and hope it's not in a join.

Affe
A: 

You can provide alternative INSERT and UPDATE statements for your entities either by Annotations or in the XML file (don't ask me for the syntax).

Just have a look at what Hibernate would originally generate (-> Log of your SQL server, its a prepared statement), and write something similar which additionally fills your audit columns.

But I am sure you already considered ON UPDATE triggers in the database and just didn't use them because you wanted to be database independent...

Daniel