I am trying to perform a DB access through a DAO object, and I have bumped into the case where I need to query a field in another Entity.
Considering two entities (EntityA and EntityB) that are connected in entity A through the foreign key EntityA.idEntityB.
I have GenericDao<EntityA> daoA and I am trying to get all the results that match a determined field of EntityB: idEntityB.fieldOfB all in the same find method of the dao.
Is it possible? And if so some directions would be nice. Thanks
edit
An example of my code:
Entities
public class EntityA {
@JoinColumn(name = "id_entity_b", referencedColumnName = "id")
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private EntityB idEntityB;
// getter+setter...
}
public class EntityB {
// ...
private String fieldOfB;
// getter+setter...
}
DAO Access
GenericDao<EntityA> daoA = // ...
Set<Criterion> filter = new HashSet<Criterion>();
filter.add(Restrictions.eq("idEntityB.fieldOfB"));
List<EntityA> list = dao.findByFilter(filter);
The error message is something like “Could not resolve property idEntityB.fieldOfB“
edit 2
I was able to find something like what I want to do. Although my API is slightly different I believe this is helful for anyone who gets across this problem at an early stage of their own project.
http://code.google.com/p/hibernate-generic-dao/
The framework features a powerful and flexible search functionality.
This is used by passing a search object to search methods on general
and generic DAOs.
Searches with nested properties are fully supported in this project.
Here is my generic Criteria filtering method.
Properties according to bean conventions have following form
foo.bar.name.With Criteria API a tree can be build from a given filtering map and Restrictions can be added. One special case I observed during testing is that filtering on the identifier property does not needs a new subcriteria since this property is already fetched.
Hope this helps you. Or have a look at the generic dao project you mentioned. I knew about this project and checked it out but never downloaded it.
Using this approach a query can be created very simple like following:
This odd approach to add the property name as the key and into the Restrictions is related to the fact that Restrictions have no getter and setter for property names.
Custom filtering
My real application uses similar code which is not restricted to
Criterionclass only.For my web tier I created custom filters which are equivalent to Restrictions api but the client does not needs hibernate jar’s anymore.
Edit
Generic filtering across non-entities such as component’s and composite-id’s is not supported. It can easily be extended with help of
ClassMetadatato support them without need for reflection. If code is needed i can provide it.