views:

228

answers:

1

I have a table with a column that will be encrypted by a trigger after the record is inserted. When I read the column, I need to apply a decrypt function in the hibernate domain class.

While saving the object, the value of the column will be saved as such. While reading the column, apply a database function on the read data. @Formula and @Column annotation cannot be applied to an attribute in the entity class. How do I achieve this functionality without using one attribute for saving and another one with @Formula for reading it?

A: 

There is a new feature in Hibernate 3.5 that lets you apply a database function during column reads and writes. Details can be found in the Column Read and Write Expressions section of the documentation. In your case, you would apply a read expression, but not a write expression, since the trigger takes care of the encryption for you.

Unfortunately, it looks like you're using Hibernate Annotations, and this feature is not yet available there. You'd need to be using XML-based mappings. Here is an example of what it would look like with both a reader and writer expression. (They're both optional.)

    <property name="creditCardNum">
        <column name="credit_card_num" not-null="true"
            write="encrypt(?)" 
            read="decrypt(credit_card_num)"/>
    </property>
Rob H