Using Hibernate v2.1
I have a dynamic app that allows users to associate textual attributes to an object. The user can use any string for the name of the attribute as well as any string for the value. Then, users can search for objects based on an attribute name and value.
Mapping document looks like (cut irrelevant aspects out):
Code:
<class name="Thing" table="Thing">
<map name="attributes" table="Thing_Attribute">
<key column="thingId"/>
<index type="string" column="mapIndex"/>
<element type="string" column="value"/>
</map>
</class>
The java class is pretty straightforward (cut irrelevant aspects out):
Code:
public class Thing
{
private Map attributes = new HashMap();
protected getAttributes() { return attributes; }
protected setAttributes(Map value) { attributes = value; }
}
My question is: how do I query for a Thing that has attribute X=x? And, I can't just query the join table directly because there are other aspects to the query (some non-dynamic fields can be queried as well) besides just the attribute.
Seems like I should be able to do something like:
Code:
...
Criteria thingCriteria = session.createCriteria(Thing.class);
Criteria attributeCriteria = thingCriteria.createCriteria("attributes");
Expression attributeName = Expression.eq(
"<WHAT GOES HERE TO REFERENCE THE mapIndex?>",
search.getAttributeName());
Expression attributeValue = Expression.eq(
"<WHAT GOES HERE TO REFERENCE THE value?>",
search.getAttributeName());
Junction junction = Expression.and(attributeName, attributeValue);
attributeCriteria.add(junction);
...
Unfortunately, I don't know what to use for property names.
I tried:
Code:
Criteria thingCriteria = session.createCriteria(Thing.class);
Criteria attributeCriteria = thingCriteria.createCriteria("attributes");
Criterion sql = Expression.sql("{alias}.mapIndex=? AND {alias}.value=?",
new Object[] {search.getAttributeName(), search.getAttributeValue()},
new Type[] {Hibernate.STRING, Hibernate.STRING});
attributeCriteria.add(sql);
This results in all Things being returned.
Please help,
Dan