springboot-mybatis 使用junit4 單元測試,單獨啓動mybatis

1. 首先再pom加入mybatis test 的jar包spring

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter-test</artifactId>
    <version>1.3.2</version>
    <scope>test</scope>
</dependency>

2. 增長單元測試類sql

//@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);
相關文章
相關標籤/搜索