package com.example.mybatisdemo.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 人民币 * @author 丁雪峰 */ public class MoneyTypeHandler extends BaseTypeHandler<Money> { @Override public void setNonNullParameter(PreparedStatement ps, int i, Money parameter, JdbcType jdbcType) throws SQLException { ps.setLong(i, parameter.getAmountMinorLong()); } @Override public Money getNullableResult(ResultSet rs, String columnName) throws SQLException { return parseMoney(rs.getLong(columnName)); } @Override public Money getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return parseMoney(rs.getLong(columnIndex)); } @Override public Money getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return parseMoney(cs.getLong(columnIndex)); } private Money parseMoney(Long value) { return Money.of(CurrencyUnit.of("CNY"), value / 100.0); } }
package com.example.mybatisdemo.mapper; import com.example.mybatisdemo.model.Coffee; import org.apache.ibatis.annotations.*; /** * @author ukyozq * @date 2020/4/11 18:29:58 */ @Mapper public interface CoffeeMapper { @Insert("insert into t_coffee (name,price,create_time,update_time)" + "values(#{name},#{price},now(),now())") //自增主键 @Options(useGeneratedKeys = true) int save(Coffee coffee); @Select("select * from t_coffee where id = #{id}") //映射关系 @Results({ @Result(id = true,column = "id",property = "id"), //mybatis.configuration.map-underscore-to-camel-case=true 可以实现一样的效果 @Result(column = "create_time",property = "createTime"), @Result(column = "update_time",property = "updateTime"), }) Coffee findById(@Param("id") Long id); }
package com.example.mybatisdemo.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.joda.money.Money; import java.util.Date; /** * Coffee * @author ukyozq */ @Data @AllArgsConstructor @NoArgsConstructor @Builder public class Coffee { private Long id; private String name; private Money price; private Date createTime; private Date updateTime; }
#xml文件 #mybatis.mapper-locations=classpath*:mapper/**/*.xml #类型别名的报名 映射时只写类名就可以了 #mybatis.type-aliases-package=类型别名的包名 #TypeHandler扫描包名 mybatis.type-handlers-package=com.example.mybatisdemo.handler #驼峰规则 _ 下划线转小驼峰 mybatis.configuration.map-underscore-to-camel-case=true
create table t_coffee ( id bigint not null auto_increment, name varchar(255), price bigint not null, create_time timestamp, update_time timestamp, primary key (id) );