前言
#博学谷IT学技术支持#
一、Springboot整合Junit
1.1回顾Spring整合Junit
1.2Springboot整合Junit
【第一步】添加整合junit起步依赖(可以直接勾选)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
【第二步】编写测试类,默认自动生成了一个
@SpringBootTest
class Springboot07JunitApplicationTests {
@Autowired
private BookService bookService;
@Test
public void testSave() {
bookService.save();
}
}
二、Springboot整合SSM
SpringBoot不存在整合Spring和SpringMVC只需要整合MyBatis
2.1回顾Spring整合MyBatis
SpringConfig
- 导入JdbcConfig
- 导入MyBatisConfig
@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MyBatisConfig.class})
public class SpringConfig {
}
JDBCConfig
- 定义数据源(加载properties配置项:driver、url、username、password)
#jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=itheima
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource getDataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
return ds;
}
}
MyBatisConfig
- 定义SqlSessionFactoryBean
- 定义映射配置
@Bean
public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("com.itheima.domain");
ssfb.setDataSource(dataSource);
return ssfb;
}
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.itheima.dao");
return msc;
}
2.2 Springboot整合Mybatis
①:创建新模块,选择Spring初始化,并配置模块相关基础信息 ②:选择当前模块需要使用的技术集(MyBatis、MySQL) ③:设置数据源参数
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
注意事项:
- SpringBoot版本低于2.4.3(不含),Mysql驱动版本大于8.0时,需要在url连接串中配置时区,或在MySQL数据库端配置时区解决此问题
jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
④:定义数据层接口与映射配置
@Mapper
public interface UserDao {
@Select("select * from tbl_book where id=#{id}")
Book getById(Integer id);
}
⑤:测试类中注入dao接口,测试功能
@SpringBootTest
class Springboot08MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
public void testGetById() {
Book book = bookDao.getById(1);
System.out.println(book);
}
}
|