package com.whn.hellospring.handler; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * 在Money与Long之间转换的TypeHandler,处理CNY和人民币 */ public class MoneyTypeHandler extends BaseTypeHandler { @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, Money money, JdbcType jdbcType) throws SQLException { preparedStatement.setLong(i,money.getAmountMinorLong()); //存储为Long类型,精确到分 } @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)); } /** * 将Long值转换为Money */ private Money parseMoney(Long value){ return Money.ofMinor(CurrencyUnit.of("CNY"),value); } }