课程名称:Java工程师2022版
课程章节:SSM开发社交网站
课程内容:
①整合其他组件:Junit单元测试、Logback日志、声明式事务
②MyBatis-Plus:是一个MyBatis的增强工具,更高效、更重要的MyBatis插件,使用简单的配置完成高效的增删改查操作,大幅提高数据库开发效率
课程收获:
整合其他组件:
1. 配置Logback日志输出
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
</dependency>
Logback.xml配置:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{HH:mm:ss} %-5level [%thread] %logger{30} - %msg%n</pattern>
<charset>GBK</charset>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="console"/>
</root>
</configuration>
2. 声明式事务配置
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
@Transactional(rollbackFor = Exception.class)
public void batchImport(){
for(int i=0;i<5;i++){
testMapper.insertSample();
}
}
声明式事务使用@Transactional注解(代码为扩大回滚范围)
3. 整合Junit单元测试
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.23</version>
</dependency>
MyBatis-Plus:
1. pom引入mybatis-plus依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.5.2</version>
</dependency>
2. Spring XML更改配置SqlSessionFactory实现类
<bean id="sessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
3. mybatis-config.xml增加MP分页插件
<!-- MyBatis Plus 3.4版本以前配置分页插件 -->
<plugins>
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin>
</plugins>
在applicationContext.xml中sessionFactory项增加新的property
<property name="plugins">
<array>
<bean class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
<property name="interceptors">
<list>
<bean class="com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor"/>
</list>
</property>
</bean>
</array>
</property>