此 SQL 查询的 HQL 等效查询

HQL eqvivalent query for this SQL query

我的实体class是

@Entity
@Table(name="SMSSalesData")
public class SMSSalesDataEntity implements Serializable{
@Id @GenericGenerator(name = "native_generator", strategy = "native")
 @GeneratedValue(generator = "native_generator")
private Integer ID;

@Column(name="CMSCode", length=50)
private String cmsCode;

@Digits(integer = 18, fraction = 2)
@Column(name = "MSQty", precision = 20)
private Double msQty;

@Digits(integer = 18, fraction = 2)
@Column(name = "HSDQty", precision = 20)
private Double hsdQty;

@Digits(integer = 18, fraction = 2)
@Column(name = "LubesQty", precision = 20)
private Double lubesQty;

@Column(name = "MobileNo", length = 20)
private String mobileNo;

@Column(name = "MsgDatetime")
@Temporal(TemporalType.TIMESTAMP)
private Date msgDatetime;

@Column(name = "CreatedDatetime", length = 20)
private Date createdDatetime;

@Column(name = "shortcode", length = 20)
private String shortcode;

@Column(name = "productcode", length = 20)
private String productcode;

@Digits(integer = 18, fraction = 2)
@Column(name = "MSStock", precision = 20)
private Double msStock;

@Digits(integer = 18, fraction = 2)
@Column(name = "HSDStock", precision = 20)
private Double hsdStock;

我希望此实体的 Hibernate 查询 class 根据 msgDateTime 的月份和年份按 msgDateTime 的月份获取 MSQty 的总和。

SELECT  SUM(MSQty) as sum_ms_qty FROM SMSSalesData where MONTH(MsgDatetime)=10 and YEAR(MsgDatetime)=2014 GROUP BY MONTH(MsgDatetime) ;

上面是这个 SQL 查询获取此 MSQty 的总和。

能否请您为我提供休眠或标准查询。 谢谢。

在 HQL 中:

SELECT sum(SMSSalesDataEntity.MSQty) as sum_ms_qty 
from SMSSalesDataEntity 
WHERE month(SMSSalesDataEntity.msgDatetime)= 10 and year(SMSSalesDataEntity.msgDatetime) = 2014 
GROUP BY month(SMSSalesDataEntity.msgDatetime)

HQL 文档:https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html

对于 dateadd 和 datediff 需要根据您要连接的数据库添加自定义函数 Date operations in HQL

SELECT SUM(MSQty) + SUM(HSDQty) FROM [essar].[dbo].[SMSSalesData] WHERE [MsgDatetime] < CURRENT_TIMESTAMP and [MsgDatetime] > DATEADD(Month, -6, CURRENT_TIMESTAMP) GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, MsgDatetime), 0); 

在 HQL 中:

SELECT SUM(SMSSalesDataEntity.MSQty) + SUM(SMSSalesDataEntity.HSDQty) FROM SMSSalesDataEntity
WHERE SMSSalesDataEntity.msgDatetime < CURRENT_TIMESTAMP AND SMSSalesDataEntity.msgDateTime >
DATEADD(MONTH, -6, CURRENT_TIMESTAMP) GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, SMSSalesDataEntity.msgDateTime), 0);