Search code examples
hibernatejpahibernate-criteria

Hiberante Criteria API exact usage with association


I am having two tables : 1.Customer_Table 2.Order_Table . There is one-to-many mapping between the tables where one customer can have multiple orders.Customer_id is primary key of Customer table and foreign key of Order table. A snippet of my Customer.hbm.xml file:

enter code here

    <set name="orders">
        <key column="Customer_id" /><!-- Customer_id acts as foreign key for Order table -->
        <one-to-many   class="Order" />
    </set>

.... I write the following snippet in my Retreive.java file to get some orders for the following customers: 1.Customer name should start with Rahul 2.Customer order description should be of type 'electronics'

Criteria criteria1 = session.createCriteria(Customer.class).
        add(Restrictions.like("customerName", "Rahul%"));`
Criteria criteria = criteria1.createCriteria("orders").add(Restrictions.like("orderDescription", "electronics%"));
List list = criteria.list();

As per my understanding Hibernate is going to perform an inner join on the two tables and return a list matching the above two criteria.

After this my requirement is to get the orderDescriptions from the resultset (List in this case) .

What java code do I exactly need to write to achieve that purpose???


Solution

  • Have finally been able to solve my issue regarding getting a restricted set of association instead of the whole association. Hope the below code snippet helps.

    Criteria criteria1 = session.createCriteria(Customer.class).
        add(Restrictions.like("customerName", "Rahul%"));`
    Criteria criteria = criteria1.createCriteria("orders","order").add(Restrictions.like("orderDescription","electronics%")).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);//order is alias to orders collection
    List<Map> list = criteria.list();
    

    Using the setResultTransformer we get a List of Map which contains the result of the inner join instead of the more traditional List of Customer.

    for(Iterator itr = list.iterator();itr.hasNext();){
    Map map = (Map)itr.next();
    Customer student = (Customer) map.get(Criteria.ROOT_ALIAS);
    Order order = (Order) map.get("order");//alias that was used earlier for orders
    }