1. 首先再pom加入mybatis test 的jar包
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter-test</artifactId> <version>1.3.2</version> <scope>test</scope> </dependency>
2. 增加单元测试类
//@SpringbootTest @MybatisTest //缓存mybatsitest注解 @RunWith(SpringJUnit4ClassRunner.class) @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) //这个是启用自己配置的数据元,不加则采用虚拟数据源 @Rollback(false) //这个是默认是回滚,不会commit入数据库,改成false 则commit public class MapperTest { @Resource Mapper mapper; @Test public void testInsert(){ Entity entity = new Entity(); entity.setAct("res"); int insert = mapper.insert(entity); System.out.println(insert); System.out.println(entity.getId()); }
3. mybatis 注解式sql编写
@Insert({"insert into otp_statistics ( ACT ) VALUES ( #{act} ) "}) // @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", resultType = Integer.class, before = false) //返回插入的id,放入entity入参中 @Options(useGeneratedKeys = true , keyProperty = "id") //只能再自增id中用,返回插入的id,放入entity入参中 int insert(OtpStatisticsEntity entity);