Search code examples
hibernatehibernate-mapping

Hibernate association using non-primary columns as criteria


I would like a read-only set relation that consists of objects that match non-pk values.

The following example table may illustrate my point:

User:
 id<pk>
 username
 alias
 Collection logs (all Log entries with log.useralias=alias and log.status>4)

Log:
 id<pk>
 status
 useralias
 message

NOTE: This is just an example, please do not comment on the usefulness of this example.

The reason I need this as a relation is perfomance: I cannot execute a query on the Logs for each User, I need a single query that initializes all the data.

Bonus question: Can this relation be initialized from a HQL query instead of expressing it as a relation? Something similar to:

from User u
  left join fetch Log l into u.logs
  where l.useralias=u.alias and l.status>4

EDIT: Please note that this is different from the Cat example:

from Cat as cat
    left join cat.kittens as kitten
        with kitten.bodyWeight > 10.0

In this case, the relation from Cat to Kittens is a foregn key->primary key relation, which would make life much simpler. In my question I do not have a foreign key, just non-pk filters.


Solution

  • JoinColumn has a referencedColumnName attribute which allows setting... the referenced column name (i.e. alias, in this case).

    Hibernate has a Where annotation allowing to specify a condition, using SQL, that the elements of a collection must verify (i.e. status > 4)