Question

I'm using Hibernate and need to perform a basic arithmetic function on the results. Here's my situation:

I'm storing odometer and fuel and would like to calculate fuelEconomy. But to do that I need to know the previous odometer reading, which would come from the previous result. Here's an illustration.

Table:

ODOMETER | FUEL
65000.0  | 5.000
65500.0  | 15.000

POJO:

public class FuelLog {
  private double odometer;
  private double fuel;
  private double fuelEconomy;

  /* Getters and Setters */
}

Can I accomplish this with Criteria or would I have to resort to an HQL Query? Or would this be better left to a different layer all together?

Was it helpful?

Solution

I would do it differently. I would store in the database the start odometer value and I would store how many KMs (or miles) the trip took:

START |  TRIP | FUEL
60000 |  5000 | 5.0
65000 | 15000 | 15.0

Then, you'd have this as your Java class:

public class FuelLog {
  private double start;
  private double trip;
  private double fuel;
}

This is the same technique usually done for recording monetary transactions for bank accounts, for instance. The only gotcha is that you must ensure that "start" is always equals to the previous start + previous trip, to avoid gaps and/or inconsistencies.

The idea is that an instance of this class should not depend on other instances to be a valid instance.

Another possible solution, which I don't think is valid in this case, would be to store the "sequence number" in the log, as an index. For instance:

START |  TRIP | FUEL | INDEX
60000 |  5000 | 5.0  | 1
65000 | 15000 | 15.0 | 2

Then, you'd have a Java class which contains a collection of FuelLog, mapped as an indexed list in Hibernate:

public class Car {
  private List<FuelLog> fuelLog;
  public double getFuelEconomy(FuelLog log){/* your implementation goes here */}
}

Car would, then, be the one responsible for calculating the fuel economy for a particular log entry, as it have access to the previous log entries. But then, you wouldn't have the fuelEconomy in your FuelLog.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top