mybtais使用TypeHandler转换器转换枚举的小例子

刚刚接触mybatis,在网上学习了mybatis使用TypeHandler,就写了一篇博客记录下,也是本人的第一篇博客。

1.创建表

CREATE TABLE tbl_user(
   id INT AUTO_INCREMENT PRIMARY KEY,
   NAME VARCHAR(20),
   age INT(2),
   sex VARCHAR(1));

2.定义枚举

public enum EnumSexType {

    NA(-1),       //无效值

    MAN(1),       //男

    WOMAN(2);   //女

    private int type;

    private EnumSexType(int type) {
        this.type = type;
    }

    public int getType() {
        return type;
    }

    public static EnumSexType int2Enum(int sexType) {
        EnumSexType[] types = EnumSexType.values();
        for (EnumSexType type : types) {
            if (type.getType() == sexType) {
                return type;
            }
        }

        return EnumSexType.NA;
    }

3.定义实体类

public class User {
    private int userId;

    private String name = "";

    private int age = -1;

    private EnumSexType sexType = EnumSexType.NA;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public EnumSexType getSexType() {
        return sexType;
    }

    public void setSexType(EnumSexType sexType) {
        this.sexType = sexType;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sexType=" + sexType +
                '}';
    }

4.定义EnumSexTypeHandler转换器实现TypeHandler,实现其方法

public class EnumSexTypeHandler  implements TypeHandler<EnumSexType> {

    @Override
    public EnumSexType getResult(ResultSet arg0, String arg1) throws SQLException {
        System.out.println("arg1   "+arg1);
        return EnumSexType.int2Enum(arg0.getInt(arg1));
    }

    @Override
    public EnumSexType getResult(ResultSet arg0, int arg1) throws SQLException {
        return EnumSexType.int2Enum(arg0.getInt(arg1));
    }

    @Override
    public EnumSexType getResult(CallableStatement arg0, int arg1) throws SQLException {
        return EnumSexType.int2Enum(arg0.getInt(arg1));
    }

    @Override
    public void setParameter(PreparedStatement arg0, int arg1, EnumSexType arg2, JdbcType arg3) throws SQLException {
        arg0.setInt(arg1, arg2.getType());
    }

}

5.编写mapper

@Mapper
@Repository
public interface UserMapper {

    /**
     * 插入用户数据。
     *
     * @param user
     */
    @Insert("insert into tbl_user ("
            + "name,"
            + "age,"
            + "sex"
            + ") values ("
            + "#{name}, "
            + "#{age},"
            + "#{sexType, typeHandler=com.cctv.chapter12.util.EnumSexTypeHandler})")
    @Options(useGeneratedKeys=true, keyProperty="userId", keyColumn="id")
    void insertUser(User user);

    /**
     * 获取所有的用户数据。
     *
     * @return
     */
    @Select("<script>select id userId, name, age, sex from tbl_user where id=#{id}</script>")
    @Results({
           /* @Result(property="userId", column="id"),
            @Result(property="name", column="name"),
            @Result(property="age", column="age"),*/
            @Result(property="sexType", column="sex", typeHandler= EnumSexTypeHandler.class)
    })
    User getAllUsers(Integer id);
}

6.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;


@Test
public void testInsert(){
    User user = new User();
    user.setAge(30);
    user.setName("xia");
    user.setSexType(EnumSexType.MAN);
    userMapper.insertUser(user);
}


@Test
public void testFind(){
    User user = userMapper.getAllUsers(1);
    System.out.println(user);
}

6.结果

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值