(2) SEARCHING FOR OBJECT(s): Now imagine theres a webpage that allows you to search any of those fields. Lets say a person enters "Boston Terrier" in the breed textfield and clicks search. I want a list of all the rescue centers that have that breed with their associated vet, vet_note, pets (
all of them), and pet_notes. In short, all the info contained in a rescue center.
Since it ignores null properties, the createCriteria().add( Example ) syntax of (1) is an easy way to return PetData objects containing that breed. I had hoped it would be as simple as replacing PetData with RescueCenter, but instead it returned all the RescueCenters, regardless if it contained a PetData of that breed or not. For example:
Code:
// Replace below with JSF backing beans
PetData petData = new PetData();
petData.setBreed( "Boston Terrier" );
Pet pet = new Pet();
pet.setData( petData );
RescueCenter rescueCenter = new RescueCenter();
rescueCenter.getPets().add( pet );
// This returns the correct PetData object
List result = session.createCriteria( PetData.class ).add( Example.create( petData ).ignoreCase() ).list();
// This returns all of the RescueCenter objects in the DB
List result = session.createCriteria( RescueCenter.class ).add( Example.create( rescueCenter ).ignoreCase() ).list();
Hibernate: select this_.idrescue_center as idrescue1_0_, this_.idvet as idvet0_0_, this_.vet_note as vet3_0_0_ from rescue_center this_ where (1=1)
What if I wanted to do a search for a breed and a particular vet. Is there a way to search for a RescueCenter without specifying every property I'm searching for like I did with createCriteria( PetData )?
I was able to get the result I wanted by using the query below, but do I have to dynamically build the where clause (excluding all the null properties) each time a search is submitted?
Code:
// It works, but I am still shaky with joins
String query = "select rc from RescueCenter as rc
join rc.pets as pet
join rc.vet as vet
join pet.data as pdata
where pdata.breed = :breed
and vet.name = :vet;
session.createQuery( query )
.setParameter( "breed", "Boston Terrier" )
.setParameter( "vet", "Tom Yugteveht" )
.list();
In short, can I populate a object that contains other objects and search for it without specifying any properties? If so, how? If not, whats a solution?