jpa

控制浮点精度:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Table(name = "CUSTOMERS")
@Entity
public class Customer {
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Integer id;
@Column(name = "Name")
private String name;
@Column(name = "Email", nullable = true, length = 128)
private String email;
@Column(name = "Age")
private int age;
@Column(name = "Remark", columnDefinition = "text")
private String remark;

@Column(name = "Salary1", columnDefinition = "decimal(5,2)")
private double salary1;
@Column(name = "Salary2", precision = 5, scale = 2)
private double salary2;
@Column(name = "Salary3", columnDefinition = "decimal(5,2)")
private BigDecimal salary3;
@Column(name = "Salary4", precision = 5, scale = 2)
private BigDecimal salary4;
......
}

数据库DDL:

1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE customers (
ID int(11) NOT NULL AUTO_INCREMENT,
Age int(11) DEFAULT NULL,
Email varchar(128) DEFAULT NULL,
Name varchar(255) DEFAULT NULL,
Remark text,
Salary1 decimal(5,2) DEFAULT NULL,
Salary2 double DEFAULT NULL,
Salary3 decimal(5,2) DEFAULT NULL,
Salary4 decimal(5,2) DEFAULT NULL,
PRIMARY KEY (ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

总结:
1.double类型将在数据库中映射为double类型,precision和scale属性无效
2.double类型若在columnDefinition属性中指定数字类型为decimal并指定精度,则最终以columnDefinition为准
3.BigDecimal类型在数据库中映射为decimal类型,precision和scale属性有效
4.precision和scale属性只在BigDecimal类型中有效