2, configure a number of data sources (H2 database). 3, configure a number of data sources (Mysql database). 【 attach source 】Spring Boot actual combat series – four, log management 【 attach source 】Spring Boot actual combat series – five, transaction abstraction 【 attach source 】Spring Boot actual combat series – six, currency storage database processing 【 attach source 】Spring Mybatis Generator automatic code generation

Introduction of depend on

  • Deal with currency dependencies
<dependency>
    <groupId>org.joda</groupId>
    <artifactId>joda-money</artifactId>
    <version>1.0.1</version>
</dependency>
Copy the code

Principle: multiply by 100 times before storing database, divide by 100 times after taking database

The code structure

Conversion of Money type to long type

  • Override the four methods of BaseTypeHandler
  • One set method, three get methods
/** * Convert TypeHandler between Money and Long to handle CNY RMB */
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);
    
Copy the code

Method of use

  • When defining entities, use the Money type directly
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Coffee {
    private Long id;
    private String name;
    private Money price;
    private Date createTime;
    private Date updateTime;
}
Copy the code

The results

Source code download address

Github.com/qiulanzhu/S…