Reputation: 625
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
)
Table car used to save car data and has a foreign key from table project. Table car_log used to save every movement in car (log). I have create object foreach this table. In this case, I want to display each car summary (sum of Gap per day) in a project. This is my query when i want to select summary of each car in project 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;
But i confuse how to handle this in HQL. I try to create new object to handle this, but confuse to use it. And I want to ask how to solve this,
public class CarLogDate {
private double km;
private Date date;
//constructor & setter getter
}
Upvotes: 0
Views: 11193
Reputation: 40328
In your query just replace table name with entity name and table column names with entity properties.
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;
Upvotes: 2
Reputation: 625
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]);
Or maybe you can instantiate the object by using Object[] a as parameter.
Upvotes: 1