【附源码】Spring Boot实战系列——六、货币存数据库的处理

732 阅读1分钟

【附源码】Spring Boot实战系列——一、配置内存数据库H2
【附源码】Spring Boot实战系列——二、配置多个数据源(H2数据库)
【附源码】Spring Boot实战系列——三、配置多个数据源(Mysql数据库)
【附源码】Spring Boot实战系列——四、日志管理
【附源码】Spring Boot实战系列——五、事务抽象
【附源码】Spring Boot实战系列——六、货币存数据库的处理
【附源码】Spring Boot实战系列——七、Mybatis Generator自动代码生成

引入依赖

  • 处理货币的依赖
<dependency>
    <groupId>org.joda</groupId>
    <artifactId>joda-money</artifactId>
    <version>1.0.1</version>
</dependency>

原理:存数据库的之前乘以100倍,取数据库后除以100倍

代码结构

Money类型和long类型的转换

  • 覆写BaseTypeHandler的四个方法
  • 1个set方法,3个get方法
/**
 * 在Money与Long之间转换的TypeHandler,处理CNY人民币
 */
public class MoneyTypeHandler extends BaseTypeHandler<Money> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Money money, JdbcType jdbcType) throws SQLException {
        preparedStatement.setLong(i, money.getAmountMinorLong());
    }


    @Override
    public Money getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return parseMoney(resultSet.getLong(s));
    }


    @Override
    public Money getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return parseMoney(resultSet.getLong(i));
    }


    @Override
    public Money getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return parseMoney(callableStatement.getLong(i));
    }


    private Money parseMoney(Long value){
        return Money.of(CurrencyUnit.of("CNY"), value/ 100.0);
    

使用方法

  • 定义实体的时候,直接使用Money类型
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Coffee {
    private Long id;
    private String name;
    private Money price;
    private Date createTime;
    private Date updateTime;
}

运行结果

源码下载地址

github.com/qiulanzhu/S…