I am working on a domain model using Hibernate for a new project. I have an entity that is basically made up of a longName:String, shortName:String and otherNames:Collection<String>.
I have been able to set this up fine, but I now want to work on some DAO features that will allow a user to find an Entity by Example, i.e. I should be able to create an Entity object and set some of the fields, then when I pass this into the search it should return a list of results that match the fields that have been set. I know I can do this using Hibernate Examples.
public List<Entity> findByExample(EntityexampleObject) {
try {
Criteria criteria = getSession().createCriteria(type);
Example example = Example.create(exampleObject).ignoreCase();
criteria.add(example);
@SuppressWarnings("unchecked")
List<Entity> list = criteria.list();
return list;
} catch (HibernateException he) {
return null;
}
}
But according to my experience and the documentation, Associations are ignored when doing this. So my collection of Strings for otherNames is ignored because it is represented in the database as an association (one-to-many).
Ideally I would like to be able to create an Entity Object and add an otherName to it, then I would be able to find any Entities where one of their Collection of otherNames matches the argument.
I tried doing:
SortedSet<String> names = exampleObject.getNames();
if (names != null && !names.isEmpty()) {
Criteria newCriteria = criteria.createCriteria("mappedNames");
newCriteria.add(Restrictions.in("string", exampleObject.getNames()));
}
Where the String literals here represent the column names used in the DB. This works in that it does join the tables and return the results where one of the otherNames in the DB match the criteria. But I get duplicates because if an Entity has two other names and the search criteria is looking for both of them then they show up as two results because the join creates two rows representing the same Entity but with each of the two other names. e.g.:
Entity:
longName:foo
shortName:bar
otherNames:
a
b
will result in two rows for the join of:
foo, bar, a
foo, bar, b
So when I do criteria.list it returns two Entity Objects, both of which are the same Object.
Does anyone know of a better way of doing a find by example using Hibernate, where the search actually looks at the association (which in this case is a simple association to a Collection of Strings)?
I think I have found the answer myself, at least to the point that it works for me. I’m still interested in other input, but for now this is what I did:
this tells it to return distinct entities and in the case of any table joining, only return the root entity.