开发者

Hibernate: Save Double to Database as Int

开发者 https://www.devze.com 2023-02-08 10:15 出处:网络
does anyone know how I can create a Java POJO which has stores a double in memory but an integer on disk?

does anyone know how I can create a Java POJO which has stores a double in memory but an integer on disk?

I would like to store these objects to disk as integers, because I have 100 million of them, and that would save space. However, sometimes my Java code manipulates the values in memory (without saving them) and turns them into real numbers

I have tried something like:

@Entity
@Table(name = "POJO")
public class POJO {
@Id
@GeneratedValue
@Column(name = "id")
int id;

@Column(name = "value")
int valueInteger; // this is weird:  in the database, we want to use integers, to save space.  but in memory, sometimes we use real values
double value;

public int getValueInteger() {
    return valueInteger;
}

public void setValueInteger(int valueInteger) {
    this.valueInteger = valueInteger;
    this.value = valueInteger;
}

public double getValue() {
    return value;
}

public void setValue(double value) {
    this.value = val开发者_开发技巧ue;
    // might want to call setValueInteger() here if consistency is required.  Right now, I think it's not, so I'll leave it out.
}
}

This is not a terrible solution, except the memory footprint is larger than needed. Is there some way to have the POJO have only a double (and the ID of course), and instruct hibernate to force a double to integer conversion when it stores to the database (for instance, by rounding that double)?

Thanks for the help!


Hope this works:

@Column(name = "value")
private int intValue;

@Transient
private Double value = null;

public double getValue() {
     if (value == null)
         value = intValue;
     return value;
}

public void setValue(double value) {
     this.value = value;
     this.intValue = value;
}


RDBMS tend to define columns in terms of precision and scale, rather than IEEE types and bit counts. If you just define a database column with fixed scale of 0 you will get the result you want when the DB automatically chops the number down.

You could define a user type object that holds it and converts, but if you're genuinely concerned about the memory footprint of a 32bit number, replacing that with a reference to a custom user type object isn't really a step forward. (Although with the behemoth that is hibernate lurking under your application code, worrying about primitive int values doesn't seem like a good place to focus your optimization efforts.)


OK I figured it out: Hibernate does all of the rounding and casting automatically. So no need for anything clever. Remove valueInteger. value will get saved to the database as an integer in the way you would except (its rounded value).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号