package com.ruoyi.common.mybatis.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 非空BigDecimal类型处理器，为空时，返回0
 * @author wjh
 * 2024/3/30
 */
public class NonNullDecimalTypeHandler extends BaseTypeHandler<BigDecimal> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BigDecimal parameter, JdbcType jdbcType) throws SQLException {
        ps.setBigDecimal(i, parameter);
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        BigDecimal data = rs.getBigDecimal(columnName);
        return data == null ? BigDecimal.ZERO : data;
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        BigDecimal data = rs.getBigDecimal(columnIndex);
        return data == null ? BigDecimal.ZERO : data;
    }

    @Override
    public BigDecimal getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        BigDecimal data = cs.getBigDecimal(columnIndex);
        return data == null ? BigDecimal.ZERO : data;
    }
}
