依赖补充
按照官方给的代码依赖是不够的,这里需要对maven的pom文件进行补充。
1 2 3 4 5 6 7 8 9 10 11 | < dependency >
< groupid >org.mybatis.spring.boot</ groupid >
< artifactid >mybatis-spring-boot-starter</ artifactid >
< version >2.2.0</ version >
</ dependency >
< dependency >
< groupid >mysql</ groupid >
< artifactid >mysql-connector-java</ artifactid >
< scope >runtime</ scope >
</ dependency >
|
数据库文件配置
这里我们还是使用mysql作为测试数据库,fm(fluent mybatis的简称)可以支持很多种数据库,暂时我们不考虑其他的数据库。
在application.properties文件中添加mysql数据库配置,至于druid连接池的使用后面的篇章用到再说。也可以用application.yml,这个随意。
1 2 3 4 | spring.datasource.username=root
spring.datasource.password= 123456
spring.datasource.url=jdbc:mysql:
spring.datasource.driver- class -name=com.mysql.jdbc.Driver
|
测试代码
再测试包中加入测试代码,主要是做一个简单的插入数据测试。
代码如下:
立即学习“Java免费学习笔记(深入)”;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.hy.fmp.test;
import com.hy.fmp.Application;
import com.hy.fmp.fluent.entity.TestFluentMybatisEntity;
import com.hy.fmp.fluent.mapper.TestFluentMybatisMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
@SpringBootTest (classes = Application. class )
public class InsertTest {
@Autowired TestFluentMybatisMapper testFluentMybatisMapper;
@Test
public void testInsertDefaultValue() {
testFluentMybatisMapper.insert(
new TestFluentMybatisEntity()
.setAge( 18 )
.setName( "法外狂徒张三" )
.setCreateTime( new Date())
.setDelFlag( 0 ));
}
}
|
说明:
1、注意TestFluentMybatisMapper是target包内的mapper类。
2、表实体TestFluentMybatisEntity可以通过链式的代码写法。
1 2 3 | @Accessors (
chain = true
)
|
增加扫描mapper注解
扫描的mapper也是target包内的mapper目录
1 2 3 4 5 6 7 8 | @SpringBootApplication
@MapperScan ({ "com.hy.fmp.fluent.mapper" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application. class , args);
}
}
|

执行测试代码
下面我们测试一下插入代码

发现这里报了个异常,调整代码,增加配置类。

代码如下,增加MapperFactory注入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | package com.hy.fmp.config;
import cn.org.atool.fluent.mybatis.spring.MapperFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationConfig {
@Bean
public MapperFactory mapperFactory() {
return new MapperFactory();
}
}
|
重新执行一下看看效果。

执行成功,看看表里的数据。ok,完美。

以上就是如何使用Java Fluent Mybatis验证对数据库的操作的详细内容,更多请关注php中文网其它相关文章!