Entity Code:
@Entity
@Table(name = "videos", indexes = { ... })
public class Video {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "uploader_id")
private Channel channel;
}
@Entity
@Table(name = "channels", indexes = { ... })
public class Channel {
@Id
@Column(name = "uploader_id", length = 30)
private String uploader_id;
}
The problematic code:
Session s = ...;
System.out.println(s.createNativeQuery(
"select videos.*, channels.* from videos left join channels on videos.uploader_id = channels.uploader_id",
Video.class).getResultList().get(0).getChannel());
The problem is that two queries are created when doing this! This is done by enabling show_sql in the properties.
Hibernate:
select
videos.*,
channels.*
from
videos
left join
channels
on videos.uploader_id = channels.uploader_id
Hibernate:
select
channel0_.uploader_id as uploader1_0_0_,
channel0_.uploader as uploader2_0_0_,
channel0_.uploader_avatar as uploader3_0_0_,
channel0_.verified as verified4_0_0_
from
channels channel0_
where
channel0_.uploader_id=?
Is there any way to only use one query? I’ve been able to do this when using the criteria api, but my query I want to write would be too complex for the criteria api.