Group By和Sum导致HQL

时间:2013-03-22 04:21:40

标签: java hibernate java-ee hql

CREATE TABLE project(
    Id int auto_increment primary key,
    Name char(50) NOT NULL
)ENGINE = InnoDB;

CREATE TABLE car(
    Id int auto_increment primary key,
    ProjectId int(11) NOT NULL,
    Plate char(10) NOT NULL,
    Latitude varchar(50) DEFAULT '-6.221165',
    Longitude varchar(50) DEFAULT '106.833286',
    LastTemp varchar(20) DEFAULT '0',
    LastSpeed varchar(20) DEFAULT '0',
    LastGap double DEFAULT 0,
    Mileage double DEFAULT 0,
    CONSTRAINT fk_car_project FOREIGN KEY(ProjectId)REFERENCES project(Id) ON UPDATE CASCADE
)ENGINE = InnoDB;

CREATE TABLE car_log(
    Id int auto_increment primary key,
    CarId int NOT NULL,
    Latitude varchar(50),
    Longitude varchar(50),
    Temp varchar(20),
    Speed varchar(20),
    Gap double DEFAULT 0,
    LogDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_carlog_car FOREIGN KEY(CarId)REFERENCES car(Id) ON UPDATE CASCADE
 )

用于保存汽车数据的表车,并且具有来自表项目的外键。表car_log用于保存汽车中的每个动作(日志)。我已经创建了对象foreach这个表。 在这种情况下,我想在项目中显示每个汽车摘要(每天的差距总和)。 当我想在项目1中选择每辆车的摘要时,这是我的查询

select CarId, DATE(LogDate) dateOnly, sum(Gap)/1000 KM from car_log where CarId IN (SELECT Id FROM car where ProjectId = 1) group by CarId, dateOnly;

但我混淆了如何在HQL中处理这个问题。我尝试创建新对象来处理这个问题,但是混淆使用它。我想问一下如何解决这个问题,

public class CarLogDate {
    private double km;
    private Date date;
    //constructor & setter getter
}

2 个答案:

答案 0 :(得分:2)

在您的查询中,只需使用实体属性替换表名和表名列。

List<Object[]> list = 
    select CarId, LogDate dateOnly, sum(Gap)/1000 KM
    from CarLogDate
    where CarId IN
        (SELECT Id FROM car where ProjectId = 1)
    group by CarId, dateOnly;

答案 1 :(得分:0)

List<Object[]> q = sessionFactory.getCurrentSession().createQuery("SELECT O.car.id AS carId, DATE(O.logDate) AS dateOnly, sum(O.gap)/1000 AS Km from CarLog O " +
            "WHERE carId IN (SELECT id FROM Car c where c.project.id = 1) GROUP BY carId, DATE(O.logDate)").list();
for(Object[] a : q)
    System.out.println(a[0]+" "+a[1]+" "+a[2]);

或许您可以使用Object [] a作为参数来实例化对象。