joda-money是用来处理金额的,数据库存储使用bigint,实体类使用Money类。
首先pom文件中加入依赖
<!--joda-money-->
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-money</artifactId>
<version>LATEST</version>
</dependency>
mybatis有一套java和数据库的对应关系,jdbc中bigint对应java的是long,所以需要做一层long到Money的转换,这时候就需要使用mybatis提供的BaseTypeHandler了,首先需要在mybatis的配置中配置handler的包路径,我使用的是javaConfig,也可以使用properties
sessionFactory.setTypeHandlersPackage("com.demo.handler");
然后在指定的包下编写handler类
/**
* 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.getAmountMajorLong());
}
@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) {
// 此处需要标明货币类型,CNY代表人民币,USD代表美元,JPY代表日元等,精度两位则100,三位则1000,以此类推
return Money.of(CurrencyUnit.of("CNY"), value / 100.0);
}
}
记住数据库使用bigint,java实体类使用Money,还有在xml的resultMap和insert字段类型配置typeHandler
// 数据库
`price` bigint(20) NOT NULL COMMENT '价格'
// 实体类
private Money price;
// resultMap
<resultMap id="BaseResultMap" type="cn.zhongguochu.demo.entity.Fruit">
<id column="id" jdbcType="VARCHAR" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="price" jdbcType="BIGINT" property="price" typeHandler="cn.zhongguochu.demo.handler.MoneyTypeHandler" />
</resultMap>
// insert语句
insert into fruit(id, name, price)
values(
#{id},
#{name},
#{price,typeHandler=cn.zhongguochu.demo.handler.MoneyTypeHandler}
)
温馨提示:在查询语句中,记得是配置resultMap,这样才能数据库的bigint到java的Money的转换。
宁静致远!