-->
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.  [ 1 post ] 
Author Message
 Post subject: How to resolve the N+1 using oneToOne
PostPosted: Wed Sep 18, 2013 4:41 am 
Newbie

Joined: Wed Jul 24, 2013 3:24 am
Posts: 2
Hi,
I assume I am having the N+1 select problem.

I got this entity:

Code:
  @Entity
    @Table(name = "Devices")
    public class Device implements Serializable {
   
     @OneToOne(mappedBy="holdingDevice", fetch=FetchType.LAZY)
        @Cascade(CascadeType.ALL)
        private WarrantyEntry warranty;



@OneToOne(fetch=FetchType.LAZY)
   @JoinColumn(name = "tradeInOldDevice")
   @Cascade(CascadeType.ALL)
   private Device tradeInOldDevice;
   
   @OneToOne(mappedBy="tradeInOldDevice", fetch=FetchType.LAZY)
   private Device tradeInNewDevice;

..

    }


This is the other entity:

Code:
  @Entity
    @Table(name = "Warranty")
    public class WarrantyEntry implements Serializable{
        private static final long serialVersionUID = 1L;
   
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Long id;
   
        @OneToOne
        @JoinColumn(name = "serial")
        private Device holdingDevice;


Now when I am starting to iterate over this loop:



Set<Device> customerDevices = user.getCustomer().getDevices();
for (Device device : customerDevices) {
...
}

I am stuck and I see in the log that Hibernate selects:

Hibernate: */ select warrantyen0_.id as...
Hibernate: /* load myclass.Device */


Hibernate: */ select warrantyen0_.id as ..
Hibernate: /* load myclass.Device */...

Over and over I guess I am having the n+1 select problem.

To try fix this I tried to use fetching this way:


Code:
    Set<Device> customerDevices = user.getCustomer().getDevices();

             String query="from Customer c left join fetch c.devices d  \n" +
                    "left join fetch d.tradeInOldDevice "  +
                    "left join fetch d.tradeInNewDevice  "+
                    "left join fetch d.warranty";
            deviceDao.getSessionFactory().openSession().createQuery(query);
         for (Device device : customerDevices) {
...
             
      }




Any idea why It still didnt fetch right?

Thanks,
ray.


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

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.