Aritz
Aritz

Reputation: 31649

Hibernate derived property with xml mapping

I have a Detectable class with a Revisions set, which are Hibernate managed POJOs. I'm also mapping my entities using hbm.xml files. When user goes to Detectable management screen, I want him to see Detectable data into a table, which will also contain the last Revision done. However the complete set of revisions will only be available accessing the detail page of the detectable.

My chance is to show the last revision date which will be loaded separately as an attribute with each Detectable instance. So I have something like that:

detectable.hbm.xml

<set name="_Revisions" table="trevision" inverse="true" lazy="true">
    <key>
        <column name="id_detectable" />
    </key>
    <one-to-many class="com.company.model.tasks.Revision" />
</set>

<property name="_LastRevisionDate"
        formula="select max(rev.start_date) from trevision rev where rev.id_detectable = _Id"
        type="date" />

That's not working and I have a SQL syntax error when hibernate tries to execute the query that is included in the formula. I've seen in different places that this property can be reached using standard SQL or HQL but I had failed with both of them. Also would it be possible to achieve the whole Revision entity (I mean the last revision) in order of the date only?

Pool your ideas!

Upvotes: 4

Views: 12300

Answers (2)

Aritz
Aritz

Reputation: 31649

I finally achieved it with this code:

<property name="_LastRevisionDate"
        formula="(select MAX(rev.start_date) from trevision rev where rev.id_detectable = id_detectable and rev.status != 'DRAFT')"
        type="date" />

Where id_detectable is my current entity key column.


UPDATE

Another workaround is to use a DB view to obtain the last revision date. Then, there's the choice to map the Entity against that view instead of the original table.

Upvotes: 5

Joe F
Joe F

Reputation: 4252

What is the sql syntax error? Did you try replacing _Id with id?

Upvotes: 1

Related Questions