使用join选择Hibernate Query语言

时间:2016-12-16 13:25:57

标签: java hibernate hql

我有两个表:session_startsession_end

session_start表的列是

session_id 
user_id

session_end表的列是

session_end_id
session_id 
session_met

现在来自user_id,我希望得到session_met的所有user。什么可以是hibernate查询呢?

2 个答案:

答案 0 :(得分:1)

class SessionStart {

  @Id
  @GeneratedValue
  @Column  
  private pid;

  @ManyToOne(fetch = FetchType.LAZY)
  private User user; 

}

class SessionEnd {

  @Id
  @GeneratedValue
  @Column  
  private pid;

  @OneToOne(fetch = FetchType.LAZY)
  private SessionStart start;

  @Column
  private String met;

}

HQL

select end.met 
  from SessionEnd end inner join SessionStart start 
  where start.user.pid = :userPid

但更好的是,在我看来,当然,要有一个表用于会话的开始和结束。

class Session {

  @Id
  @GeneratedValue
  @Column  
  private pid;

  @ManyToOne(fetch = FetchType.LAZY)
  private User user;

  @Column
  private String met; 

}

答案 1 :(得分:0)

我们需要你的hibernate映射来为它创建一个HQL。否则它将是纯SQL,如:

select e.session_met
       from session_start s
       join session_end e on s.session_id = e.session_id
where  s.user_id = ?

对于HQL,您需要加入属性,例如

join s.property to session_end on session_start object