本节讲述Spring和MyBatis的整合,但是还有一部分其他组件需要配置,所以整合在了一起,代码有标明第三部分。
以下代码可以参考此图
org.springframework
spring-jdbc
5.2.6.RELEASE
org.mybatis
mybatis
3.5.4
org.mybatis
mybatis-spring
2.0.3
mysql
mysql-connector-java
8.0.16
com.alibaba
druid
1.1.14
org.springframework
spring-test
5.2.6.RELEASE
junit
junit
4.12
javax.servlet
javax.servlet-api
3.1.0
provided
ch.qos.logback
logback-classic
1.2.3
%d{HH:mm:ss} %-5level [%thread] %logger{30} - %msg%n
UTF-8
package com.imooc.reader.mapper;
/**
* @ClassName TestMapper
* @Description TODO
* @date 2021/5/7 17:07
* @Param
* @return
*/
public interface TestMapper {
public void insert();
}
insert into test(content) values('测试内容')
package com.imooc.reader.service;
import com.imooc.reader.mapper.TestMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* @ClassName TestService
* @Description 测试类
* @date 2021/5/7 17:11
* @Param
* @return
*/
@Service
public class TestService {
@Resource
private TestMapper testMapper;
// 事务控制注解:运行成功则进行全局提交,失败则全局回滚
// 要么全部要么什么都不做
// 这让我想起了初中充值饭卡的经历: 一百元分两次五十充值,可是系统只记录了一次五十,找学校多次都无果
@Transactional
public void batchImport() {
for (int i = 0; i < 5; i++) {
// 事务提交测试
// if (i == 3) {
// throw new RuntimeException("预期外异常");
// }
testMapper.insert();
}
}
}
package com.imooc.reader.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import static org.junit.Assert.*;
// 自动初始化IOC容器
@RunWith(SpringJUnit4ClassRunner.class)
// 声明配置文件在什么地方
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestServiceTest {
// 注入TestService
@Resource
private TestService testService;
@Test
public void batchImport() {
testService.batchImport();
System.out.println("批量导入成功");
}
}
4.0.0
org.example
imooc-reader
1.0-SNAPSHOT
aliyun
aliyun
https://maven.aliyun.com/repository/public
org.springframework
spring-webmvc
5.2.6.RELEASE
org.freemarker
freemarker
2.3.30
org.springframework
spring-context-support
5.2.6.RELEASE
com.fasterxml.jackson.core
jackson-core
2.11.0
com.fasterxml.jackson.core
jackson-annotations
2.11.0
com.fasterxml.jackson.core
jackson-databind
2.11.0
org.springframework
spring-jdbc
5.2.6.RELEASE
org.mybatis
mybatis
3.5.4
org.mybatis
mybatis-spring
2.0.3
mysql
mysql-connector-java
8.0.16
com.alibaba
druid
1.1.14
org.springframework
spring-test
5.2.6.RELEASE
junit
junit
4.12
javax.servlet
javax.servlet-api
3.1.0
provided
ch.qos.logback
logback-classic
1.2.3
text/html;charset=utf-8
application/json;charset=utf-8
UTF-8
%d{HH:mm:ss} %-5level [%thread] %logger{30} - %msg%n
UTF-8
insert into test(content) values('测试内容')
yBatis配置文件