简体   繁体   English

如何使用Hibernate保留PRICE信息

[英]How to persist PRICE information using Hibernate

In SQL it is a usual practice to store money amounts in columns of type DECIMAL(10,2) . 在SQL中,通常将金额存储在DECIMAL(10,2)类型的列中。 However when it comes to Hibernate mapping, I'd wish to avoid mapping values to floating point numbers. 但是,当涉及到Hibernate映射时,我希望避免将值映射到浮点数。 Is there a way to map column to an integer containing number of cents? 有没有一种方法可以将列映射到包含美分的整数?

The practice of using a decimal(10,2) for money is terrible. 使用十进制(10,2)赚钱的做法很糟糕。 Also, the practice of using a floating point value for money is a monkey technique (as in, only a monkey would think it makes sense to store a fixed point value with a non-exact, floating point number). 同样,使用浮点数作为货币的做法是一种猴子技术(例如,只有猴子会认为用不精确的浮点数存储定点值是有意义的)。

Instead, determine the smallest monetary value that you need to store, for example 1/1000 of a euro, and store money as an integral multiple of that value. 相反,请确定您需要存储的最小货币值,例如1/1000欧元,然后将货币存储为该值的整数倍。 Continuing this example, the value 2.57 euros would be represented by 2570 in the money column. 继续该示例,值2.57欧元将在money栏中由2570表示。

Money math should always be performed with integral values. 金钱数学应始终以整数值执行。

Side note: 边注:

Proof of monkey: 猴子证明:

float value1 = .1;
float value2 = .2;
float value3 = value1 + value2;

if (value3 == .3)
    printf ("m1. you are not a monkey");
else
    printf ("m2. you are a monkey.  learn something about floating point representation");

message m1 will never display 消息m1将永远不会显示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM