-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 9 posts ] 
Author Message
 Post subject: ScrollableResults and DISTINCT_ROOT_ENTITY
PostPosted: Wed Oct 15, 2008 3:31 pm 
Newbie

Joined: Wed Oct 15, 2008 3:17 pm
Posts: 3
For example I have the following pojo:
Contact with a relation one to many with Telephone.

So I want to use the ScrollableResults.

If i have 1 contact with 3 phone numbers, in my ScrollableResults i have 3 records.

So if i apply the DISTINCT_ROOT_ENTITY on the ScrollableResults, always 3 results. Normal I think.

But i would like know if it is easly possible to "merge" the 3 results in order to have 1 entity Contact with the 3 phones numbers.


Last edited by hibernatus1234 on Wed Oct 15, 2008 4:41 pm, edited 1 time in total.

Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 15, 2008 4:35 pm 
Newbie

Joined: Tue Nov 01, 2005 2:00 pm
Posts: 10
You want to do a fetch join.
http://www.hibernate.org/315.html
Here's an HQL example : http://forum.hibernate.org/viewtopic.php?t=991539


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 15, 2008 4:44 pm 
Newbie

Joined: Wed Oct 15, 2008 3:17 pm
Posts: 3
No not workink your solution i post an example:


Code:
                        Contact contact = new Contact();
         contact.setFirstName("Deepak");

         Telephone telephone = new Telephone();
         telephone.setNumero("05 00 00 00 00");
         telephone.associateContact(contact);

         Telephone telephone2 = new Telephone();
         telephone2.setNumero("05 11 11 11 11");
         telephone2.associateContact(contact);

         session.save(contact);

         System.out.println("Done");
         session.flush();
         session.clear();

         Criteria criteria = session.createCriteria(Contact.class);
         criteria.createAlias("telephones", "telephone",
               CriteriaSpecification.LEFT_JOIN);
         criteria.add(Restrictions.idEq(contact.getId()));
         ScrollableResults scrollableResults = criteria
               .scroll(ScrollMode.FORWARD_ONLY);
         criteria
               .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
         
         int i = 1;
         while (scrollableResults.next()) {
            session.clear();
            System.out.println("Iteration " + i);
            final Iterator<Telephone> telephones = ((Contact) scrollableResults
                  .get(0)).getTelephones().iterator();
            while (telephones.hasNext()) {
               System.out.println("Num tel:"
                     + telephones.next().getNumero());
            }
            i++;
         }



The result:
Iteration 1
Num tel:05 00 00 00 00
Iteration 2
Num tel:05 11 11 11 11


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 15, 2008 5:08 pm 
Newbie

Joined: Tue Nov 01, 2005 2:00 pm
Posts: 10
Take a look at the example and docs again. You didn't set the fetch mode for the left join.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 15, 2008 5:26 pm 
Newbie

Joined: Wed Oct 15, 2008 3:17 pm
Posts: 3
I don't understand can you send me the line to be added and i will test your solution please.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Oct 16, 2008 11:30 am 
Newbie

Joined: Tue Nov 01, 2005 2:00 pm
Posts: 10
There is a setFetchMode() method for the criteria query.
Also, the example I sent you is the exact query you need. You just need to modify the specifics and add your where clause.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 22, 2008 2:53 pm 
Newbie

Joined: Thu May 01, 2008 9:34 pm
Posts: 7
I'm having the same issue. But i did not use Criteria API. My query looks like "from Item i left join fetch i.properties" where an item has multiple properties.

Here is the code.
Query q = null;
ScrollableResults results = null;

q = session.createQuery("from Item i left join fetch i.properties");
q.setCacheMode(CacheMode.IGNORE);
q.scroll(ScrollMode.FORWARD_ONLY);

results.next();
results.get(0);

I get items with their first property initialized. But the rest of properties cannot be found in the association. I checked the database and also ran the query Hibernate generated in SQL console. Properties are there in db. Any idea?

Thanks
-w


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 22, 2008 5:17 pm 
Newbie

Joined: Thu May 01, 2008 9:34 pm
Posts: 7
Ok. Now I found the problem. It has nothing to do with Hibernate. I was using c3p0 connection pool version 0.9.1 jar. Now I have updated to 0.9.1.2 jar and it works!


Top
 Profile  
 
 Post subject: Re: ScrollableResults and DISTINCT_ROOT_ENTITY
PostPosted: Thu Sep 23, 2010 12:53 pm 
Newbie

Joined: Thu Sep 23, 2010 12:46 pm
Posts: 1
Dear All,

I have a problem using the Criteria API with DISTINCT_ROOT_ENTITY and ScrollableResults, which I wanted to use for efficient paging of large result sets.

It seems that DISTINCT_ROOT_ENTITY is ignored then, even if I use setFetchMode(associationPath, FetchMode.JOIN).

Could you kindly help me with the right command to run to get back ScrollableResults with 4 distinct person entities with their event collections correctly populated? Run the following code, list() yields 4 - correct; using scroll() yields 11, i.e. the root transformer did not run.

Thanks,
Oren

Code:
public class LTestScrollableResults extends <somefixtureclassnotincludedhere>
{
   // ========================= CONSTANTS =================================

   /**
    * A logger that helps identify this class' printouts.
    */
   private static final Logger log = getLogger(LTestScrollableResults.class);

   // ========================= DEPENDENCIES ==============================

   // ========================= TESTING METHODS ===========================

   /**
    * Tests that <code>DISTINCT_ROOT_ENTITY</code> collocates entities in list mode.
    */
   @Test
   @Transactional
   public void distinctRootEntityWithListResults()
   {
      if (log.isDebugEnabled())
      {
         log.debug("============== List Test ==============");
      }
      final GenericCriteria hibernateCriteria = personAndEventsCriteria();
      final List<?> result = hibernateCriteria.list();
      assertEquals(4, result.size());
   }

   /**
    * Tests that <code>DISTINCT_ROOT_ENTITY</code> collocates entities in scroll mode.
    */
   @Test
   @Transactional
   public void distinctRootEntityWithScrollableResults()
   {
      if (log.isDebugEnabled())
      {
         log.debug("============== ScrollableResults Test ==============");
      }
      final GenericCriteria hibernateCriteria = personAndEventsCriteriaScrollableResults();
      final List<?> result = HibernateUtil.scrollAsList(hibernateCriteria,
            ScrollMode.FORWARD_ONLY);

      // Until FUR-1274 is resolved
      // assertEquals(4, result.size());
      assertEquals(11, result.size());
   }

   // ========================= PRIVATE METHODS ===========================

   /**
    * @return
    */
   private GenericCriteria personAndEventsCriteria()
   {
      // Main criteria: a single criterion of ID in (result of ID sub-select)
      return personCriteria(CRITERIA)
            .addAlias("Event", "this.events")
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            .add(Restrictions.like("Event.eventName", "Event", MatchMode.START));
   }

   /**
    * @return
    */
   private GenericCriteria personAndEventsCriteriaScrollableResults()
   {
      // Main criteria: a single criterion of ID in (result of ID sub-select)
      return personCriteria(CRITERIA)
            .addAlias("Event", "events")
            .setFetchMode("events", FetchMode.JOIN)
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            .setCacheMode(CacheMode.IGNORE)
            .add(Restrictions.like("Event.eventName", "Event", MatchMode.START));
   }

   /**
    * @param criteriaType
    * @return
    */
   private GenericCriteria personCriteria(final CriteriaType criteriaType)
   {
      return criteria(criteriaType, ComplexPersonEntity.class,
            sessionFactory.getCurrentSession());
   }
}


ComplexPersonEntity.java:
Code:
@Entity
@Table(name = "Person")
public class ComplexPersonEntity implements PersistentEntity<Long>
{
    // ========================= CONSTANTS =================================

    /**
     * Serial ID.
     */
    @Transient
    private static final long serialVersionUID = -2801577767291743796L;

    // ========================= FIELDS ====================================

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "person", targetEntity = ComplexEventEntity.class)
    private Collection<ComplexEventEntity> events;

    // ========================= IMPL: PersistentEntity ====================

    /**
     * @return the id
     */
    @Override
    public Long getId()
    {
        return id;
    }

    // ========================= GET & SET =================================

    /**
     * @return the name
     */
    public String getName()
    {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(final String name)
    {
        this.name = name;
    }

    /**
     * @return the events
     */
    public Collection<ComplexEventEntity> getEvents()
    {
        return events;
    }

    /**
     * @param events
     *            the events to set
     */
    public void setEvents(final Collection<ComplexEventEntity> events)
    {
        this.events = events;
    }

}


ComplexEventEntity.java:
Code:
@Entity
@Table(name = "Event")
public class ComplexEventEntity implements PersistentEntity<Long>
{
    // ========================= CONSTANTS =================================

    /**
     * Serial ID
     */
    @Transient
    private static final long serialVersionUID = 7578943207653776849L;

    // ========================= FIELDS ====================================

    /**
     * Id of the event
     */
    @Id
    @GeneratedValue
    private Long id;

    /**
     * The event name
     */
    @Column(name = "event")
    private String eventName;

    @ManyToOne
    @JoinColumn(name = "person_id")
    private ComplexPersonEntity person;

    // ========================= IMPL: PersistentEntity ====================

    /**
     * @return the id
     */
    @Override
    public Long getId()
    {
        return id;
    }

    // ========================= GET & SET =================================

    /**
     * @param id
     *            the id to set
     */
    public void setId(final Long id)
    {
        this.id = id;
    }

    /**
     * @return the eventName
     */
    public String getEventName()
    {
        return eventName;
    }

    /**
     * @param eventName
     *            the eventName to set
     */
    public void setEventName(final String eventName)
    {
        this.eventName = eventName;
    }

    /**
     * @return the person
     */
    public ComplexPersonEntity getPerson()
    {
        return person;
    }

    /**
     * @param person
     *            the person to set
     */
    public void setPerson(final ComplexPersonEntity person)
    {
        this.person = person;
    }

}


import.sql data:
Code:
INSERT INTO Person (id, name) VALUES (1, 'John Doe');
INSERT INTO Person (id, name) VALUES (2, 'John Doe');
INSERT INTO Person (id, name) VALUES (3, 'John Doe');
INSERT INTO Person (id, name) VALUES (4, 'John Doe');
INSERT INTO Person (id, name) VALUES (5, 'Jane Doe');
INSERT INTO Person (id, name) VALUES (6, 'Jack Doe');
INSERT INTO Person (id, name) VALUES (7, 'Jill Doe');

INSERT INTO Event (id, event, person_id) VALUES (1, 'Event 1', 1)
INSERT INTO Event (id, event, person_id) VALUES (2, 'Event 1', 1)
INSERT INTO Event (id, event, person_id) VALUES (3, 'Event 1', 1)
INSERT INTO Event (id, event, person_id) VALUES (4, 'Event 1', 1)
INSERT INTO Event (id, event, person_id) VALUES (5, 'Event 1', 5)
INSERT INTO Event (id, event, person_id) VALUES (6, 'Event 2', 5)
INSERT INTO Event (id, event, person_id) VALUES (7, 'Event 1', 6)
INSERT INTO Event (id, event, person_id) VALUES (8, 'Event 2', 6)
INSERT INTO Event (id, event, person_id) VALUES (9, 'Event 1', 7)
INSERT INTO Event (id, event, person_id) VALUES (10, 'Event 2', 7)
INSERT INTO Event (id, event, person_id) VALUES (11, 'Event 3', 5)


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 9 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.