0

Consider the following setup.

Space.java

class Space {

    Id id;

    ParkingCampus campus;
}

class ParkingCampus {

    Id id;

    String country;

 }

This is not the exact structure of my project but it is close enough for what I am trying to understand.

How would I be able to run a query on my 'Space' object which only returns instances where the child class 'ParkingCampus' has the String 'country' set to a specific value, eg: "UK".

I was thinking something like:

 sessionFactory.getCurrentSession()
   .createCriteria(String.class)
   .add(Restrictions.eq("country", "UK"))
    .list();

But i'm not sure if that would compile correctly. So does Hibernate by default do a 'deep' search in an attempt to map results to my restriction criteria or do I need to do something else to specify the query to work in this way?

Any help would be greatly appreciated!

Adam
  • 1,724
  • 13
  • 16

1 Answers1

1

Use Space as the base criteria, create an alias for the parking campus, and add a restriction on the alias' child country to UK.

However, keep in mind that your implementation seems a bit off, IMO. There should be a table with a compound key of parkingCampusId and spaceId, rather than the Space owning the id.

Criteria criteria =  sessionFactory.getCurrentSession().createCriteria(Space.class, "space");
criteria.createAlias("space.parkingCampus", "campus");
criteria.add(Restrictions.eq("campus.country", "UK");
Compass
  • 5,867
  • 4
  • 30
  • 42
  • Hi, thanks for your response. Considering the entities in a table I would agree with you that the space should have a campus id field. However, and correct me if I am wrong, is the point of Hibernate not that it should help map those relations for me? So to say that after getting a space I should be able to also define the associated campus. Instead of having to do a search on first the space and then the campus id to get the result I want? – Adam Jul 08 '16 at 22:34
  • Initially, yes, but you will want to use a Many-to-one mapping: http://www.tutorialspoint.com/hibernate/hibernate_many_to_one_mapping.htm basically, what you have is suitable as a "rough sketch" but you want to implement the relationships so that the Campus, for example, brings with it a lazy collection of spaces that you can work with. – Compass Jul 08 '16 at 23:00