感受:整合后只需要一个application.properties配置文件即可,感觉项目瘦身了。mybatis相关mapper.xml最好不要使用注解,这样子会降低代码的可读性、可维护性。
整合步骤:
1导入相关依赖
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- mybatis相关依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- 数据库连接池 -->
<!--<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>-->
<!--JSON-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
2增加启动类DemoApplication
@SpringBootApplication
@MapperScan("com.zoie.restaurant.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3增加配置文件application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8
spring.datasource.username =username
spring.datasource.password =password
#如果不使用默认的数据源 (com.zaxxer.hikari.HikariDataSource)
#spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
#mybatis
mybatis.configuration.lazy-loading-enabled=true
mybatis.configuration.aggressive-lazy-loading=false
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.type-aliases-package=com.zoie.restaurant.entity
mybatis.mapper-locations=classpath:mapper/*.xml
#mybatis sql打印
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
4service实现增加事务
@Service
@Transactional
public class TUserServiceImpl implements TUserService {
@Resource
TUserMapper tUserMapper;
@Override
public TUser getById(Long id) {
return tUserMapper.selectByPrimaryKey(id);
}
@Override
public List<TUser> getAll() {
return tUserMapper.selectAll();
}
@Override
public int update(TUser tUser) {
return tUserMapper.updateByPrimaryKey(tUser);;
}
@Override
public int deleteById(Long id) {
return tUserMapper.deleteByPrimaryKey(id);
}
}
5新建controller类测试增删改查
@RestController
@RequestMapping("/demo/user")
public class TUserController {
@Resource
TUserService tUserService;
@GetMapping("get_by_id")
public String getById(Long id) {
return JSON.toJSONString(tUserService.getById(id));
}
@GetMapping("get_all")
public String getAll() {
return JSON.toJSONString(tUserService.getAll());
}
@GetMapping("update_user")
public String updateUser(TUser tUser) {
tUser.setId(5L);
tUser.setName("汪涵yuee");
tUser.setPhone("11111111");
return JSON.toJSONString(tUserService.update(tUser));
}
@GetMapping("delete_by_id")
public String deleteById(Long id){
return JSON.toJSONString(tUserService.deleteById(id));
}
}