|
| 1 | +package com.test; |
| 2 | + |
| 3 | +import org.apache.ibatis.session.SqlSessionFactory; |
| 4 | +import org.apache.ibatis.type.EnumTypeHandler; |
| 5 | +import org.apache.ibatis.type.TypeHandler; |
| 6 | +import org.apache.ibatis.type.TypeHandlerRegistry; |
| 7 | +import org.example.Application; |
| 8 | +import org.example.entity.User; |
| 9 | +import org.example.enums.GcType; |
| 10 | +import org.example.mapper.UserMapper; |
| 11 | +import org.example.mapper.UserMapper.RequestParam; |
| 12 | +import org.example.typehandler.CustomEnumTypeHandler; |
| 13 | +import org.junit.Test; |
| 14 | +import org.junit.runner.RunWith; |
| 15 | +import org.springframework.beans.factory.annotation.Autowired; |
| 16 | +import org.springframework.boot.test.context.SpringBootTest; |
| 17 | +import org.springframework.test.context.junit4.SpringRunner; |
| 18 | +import org.springframework.transaction.annotation.Transactional; |
| 19 | + |
| 20 | +import static org.junit.Assert.assertEquals; |
| 21 | + |
| 22 | +@RunWith(SpringRunner.class) |
| 23 | +@SpringBootTest(classes = Application.class) |
| 24 | +@Transactional |
| 25 | +public class MybatisTest { |
| 26 | + @Autowired |
| 27 | + private SqlSessionFactory sqlSessionFactory; |
| 28 | + @Autowired |
| 29 | + private UserMapper userMapper; |
| 30 | + |
| 31 | + @Test |
| 32 | + public void testEnumTypeHandler() { |
| 33 | + User user = new User(); |
| 34 | + user.setUu("user1"); |
| 35 | + user.setType(GcType.G1); |
| 36 | + |
| 37 | + // insert into user (uu, `type`) values ('user1', '1'); |
| 38 | + userMapper.insert(user); |
| 39 | + |
| 40 | + TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry(); |
| 41 | + |
| 42 | + TypeHandler<GcType> typeHandler = typeHandlerRegistry.getTypeHandler(GcType.class); |
| 43 | + |
| 44 | + // here |
| 45 | + assertEquals(typeHandler.getClass(), CustomEnumTypeHandler.class); |
| 46 | + |
| 47 | + RequestParam req = new RequestParam(); |
| 48 | + req.setGcType(GcType.ZGC); |
| 49 | + |
| 50 | + // actual: select * from user where `type` = 'ZGC'; |
| 51 | + // expected: select * from user where `type` = 2; |
| 52 | + userMapper.selectByRequestParam(req); |
| 53 | + |
| 54 | + TypeHandler<GcType> typeHandler2 = typeHandlerRegistry.getTypeHandler(GcType.class); |
| 55 | + |
| 56 | + // here |
| 57 | + assertEquals(typeHandler2.getClass(), EnumTypeHandler.class); |
| 58 | + } |
| 59 | +} |
0 commit comments