2、修改资源目录resources下的application.yml配置文件,添加数据库等配置org.mybatis.spring.boot mybatis-spring-boot-starter1.3.2 mysql mysql-connector-javaruntime
spring:
datasource:
#驱动名称,srpingboot2.0之后不再使用com.mysql.jdbc.Driver
driver-class-name: ${datasource_dirver:com.mysql.cj.jdbc.Driver}
#数据库链接地址
url: ${datasource_url:jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull}
#数据库密码
password: ${datasource_password:password}
#数据库登录用户名称
username: ${datasource_username:root}
#数据库初始连接数
initial-size: ${datasource_initSize:5}
#数据库最小空闲数
min-idle: ${datasource_minIdel:10}
#数据库最大连接等待时间
max-wait: 60000
#数据库最大连接
max-active: ${datasource_maxActive:50}
#验证数据库连接的有效性
validationgQuery: SELECt 'X'
3、在资源文件夹下创建mapper文件夹,用来存放编写动态SQL的Mapper.xml文件
4、继续改application.yml配置文件,指定资源文件Mapper.xml位置以及日志打印级别
mybatis:
#mapper.xml文件存放位置
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.taneki.code.entity
#日志打印级别
logging:
level:
com:
taneki:
code:
mapper: debug
5、编写DemoMapper接口类,在DemoMapper添加@Repository声明这是一个DAO接口,然后编写一条简单的查询
@Repository
public interface DemoMapper {
long selectCount(@Param("beginDate")Date beginDate, @Param("endDate") Date endDate);
}
对应的DemoMapper.xml编写SQL语句
6、SpringBoot启动类开启Mapper包扫描
@SpringBootApplication
@MapperScan("com.taneki.code.mapper")
public class CodeApplication {
@Resource
private RestTemplateBuilder builder;
public static void main(String[] args) {
SpringApplication.run(CodeApplication.class, args);
}
@Bean
RestTemplate restTemplate() {
return builder.build();
}
}
7、使用单元测试进行测试
第一步,引入springtest和junit依赖
org.springframework.boot spring-boot-starter-testtest junit junit4.12 test
第二步,在test测试目录下新建用来测试的基类,引入@SpringBootTest和@RunTest注解,后续所有单元测试类都可以继承这个基类,不用重复引入这两个注解
@SpringBootTest(classes = CodeApplication.class)
@RunWith(SpringRunner.class)
public class baseTest {
}
第三步,新建单元测试进行测试
@Slf4j
public class DemoTest extends baseTest{
@Autowired
private DemoMapper demoMapper;
@Test
public void demoTest(){
Date beginDate = new Date();
Date endDate = DateUtils.getDateAfter(beginDate, 1);
long count = demoMapper.selectCount(beginDate, endDate);
log.info("统计数量: {}", count);
}
}
8、因SpringBoot版本导致的报错,将SpringBoot版本号从2.6.1降低为2.4.0,运行正常
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfigurationGeneric.clas
修改为 org.springframework.boot spring-boot-starter-parent2.6.1 org.springframework.boot spring-boot-starter-parent2.4.0



