复制代码
resources 目录下创建 sql 文件夹,并创建两个 .sql 文件,分别声明数据库表的结构和数据:
create table if not exists sys_department (
id varchar(32) not null primary key,
name varchar(32) not null
);
insert into sys_department (id, name) values (‘idaaa’, ‘testaaa’);
insert into sys_department (id, name) values (‘idbbb’, ‘testbbb’);
insert into sys_department (id, name) values (‘idccc’, ‘testccc’);
insert into sys_department (id, name) values (‘idddd’, ‘testddd’);
复制代码
[](()编写测试代码
下面就可以按照三层架构来写一些很简单的测试代码了。
[](()DemoDao
这里咱就不整合 MyBatis / Hibernate 了,直接使用原生的 JdbcTemplate 就可以:
@Repository
public class DemoDao {
@Autowired
JdbcTemplate jdbcTemplate;
public List
[](()DemoService + DemoService2
声明一个会触发抛出运行时异常的方法,并标注 @Transactional 注解:
@Service
public class DemoService {
@Autowired
DemoDao demoDao;
@Transactional(rollbackFor = Exception.class)
public void doTransaction() {
demoDao.save(“aaaaaaaa”);
int i = 1 / 0;
demoDao.update(“18”, “ccc”);
}
}
复制代码
DemoService2 同样的代码,仅仅是类名不同,代码不再贴出。
[](()DemoController
Controller 里面同时依赖这两个 Service :
@RestController
public class DemoController {
@Autowired
DemoService demoService;
@Autowired
DemoService2 demoService2;
@GetMapping(“/doTransaction”)
public String doTransaction() {
demoService.doTransaction();
return “doTransaction”;
}
@GetMapping(“/doTransaction2”)
public String doTransaction2() {
demoService2.doTransaction();
return “doTransaction2”;
}
}
复制代码
[](()Realm依赖Service
最后&#x