Reputation: 978
I'm trying to write a piece of code to fetch all of the ContactDevices with their associated Contact at once as a list (through execution of only one sql-statement).
Criteria sq = session.createCriteria(ContactDevice.class)
.setFetchMode("contact", FetchMode.JOIN);
List<ContactDevice> contactList = (List<ContactDevice>) sq.list();
The problem is for every ContactDevice
, hibernate fetches it's associated Contact
through running a separate sql-statement which makes my program considerably slow, I mean hibernate runs this for each ContactDevice
to get it's associated Contact
:
select * from Contact contact0_ where contact0_.ContactID=?
I also tried a seemingly more manual approach but still couldn't prevent hibernate, Is there any way that I can do this by the cost of only running one sql-statement ?
@Entity
public class Contact {
@Id
@Column(name = "ContactID")
private Integer id;
private String firstName;
private String secondName;
private String avatarPath;
}
@Entity
public class ContactDevice {
@Id
@OneToOne
@JoinColumn(name = "ContactID", referencedColumnName = "ContactID")
private Contact contact;
private String phoneNumber;
private String deviceType;
}
Upvotes: 0
Views: 45
Reputation: 978
Thanks guys, your hints helped me a lot. And at last I figured a way and it was to disable the proxy
to get rid of this persisting laziness !
public class ContactDevice {
@Id
@OneToOne
@LazyToOne(LazyToOneOption.NO_PROXY)
@JoinColumn
private Contact contact;
.....
}
Now tuples could be retrived through both
Criteria sq = session.createCriteria(ContactDevice.class).setFetchMode("contact", FetchMode.JOIN)
or
Query query = session.createQuery("select cd from ContactDevice cd join fetch cd.contact");
Upvotes: 1
Reputation: 153940
Try with a simple HQL query like this:
Query query = session.createQuery("select cd from ContactDevice cd join fetch cd.contact");
List list = query.list();
Upvotes: 0