0
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 用于保存汽车数据,并具有表项目的外键。表 car_log 用于保存 car 中的每一个动作(日志)。我已经为这个表创建了对象。在这种情况下,我想在一个项目中显示每辆车的摘要(每天的 Gap 总和)。这是我想在项目 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
}
4

2 回答 2

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;
于 2013-03-22T04:59:57.363 回答
1
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 作为参数来实例化对象。

于 2013-03-22T06:17:31.857 回答