有人可以帮我将以下MySQL查询转换为HQL。
SELECT COUNT(*), DATE_FORMAT(insert_datetime, '%Y%m%d') as onlyDate
FROM ticket
WHERE
DATE( insert_datetime ) = DATE( NOW() ) AND
status not in ( 1, 2, 6)
GROUP BY onlyDate;
在上面的查询中,我试图获取当天(仅限日期而非时间)的门票数量,这些门票必须具有特定状态。
实体Bean如下所示
@Entity
@Table(name="ticket")
public class TicketBean implements IPersistable {
private static final long serialVersionUID = 1L;
private Long ticketId;
private Integer status;
private Date insertDatetime;
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
@Column(name="ticket_id")
public Long getTicketId() {
return ticketId;
}
public void setTicketId(Long ticketId) {
this.ticketId = ticketId;
}
@Column(name="insert_datetime")
public Date getInsertDatetime() {
return insertDatetime;
}
public void setInsertDatetime(Date insertDatetime) {
this.insertDatetime = insertDatetime;
}
@Column(name="status")
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
答案 0 :(得分:0)
为了使您的查询具有可移植性,我将省略部分DATE_FORMAT(insert_datetime, '%Y%m%d')
并对此查询进行编码:
SELECT COUNT(tb), tb.insertDatetime AS onlyDate
FROM TicketBean tb
WHERE
tb.insertDatetime = CURRENT_DATE AND
tb.status not in (1, 2, 6)
GROUP BY onlyDate
您可以使用DateFormatter
格式化服务器端的日期。
请注意,您还可以在JPQL
中使用本机数据库功能。如果您只是按原样编写函数调用,大多数提供程序都不会抱怨。从JPA 2.1起,你可以称之为"很好地":
SELECT FUNCTION('DATE_FORMAT', tb.insertDatetime, '%Y%m%d') AS onlyDate