spring-boot简单整合mybatis(基于XML版本)
1、项目结构
2.添加maven依赖
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
3.application.yml配置信息
spring:
profiles:
active: dev
#mybatis参数
mybatis:
type-aliases-package: com.entity
mapper-locations: classpath:mapper/*.xml
---
#开发配置
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost:3306/springboot
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
4.创建数据库
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'yunxi.shi');
5.创建实体、编写mapper接口和映射文件(这个可以通过mybatis生成器生成)
略...
参考博客:spring-boot番外篇2:mybatis-generator-1.35-master 生成器使用
6.编写service接口业务层
package com.service;
import com.entity.User;
public interface UserService {
public User selectById(Integer id);
}
package com.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.dao.UserMapper;
import com.entity.User;
import com.service.UserService;
@Service
public class UserImpl implements UserService{
@Resource
private UserMapper userDao;
@Override
public User selectById(Integer id) {
return userDao.selectByPrimaryKey(id);
}
}
7.编写controller
package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.entity.User;
import com.service.UserService;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getById")
public User getById(Integer id){
return userService.selectById(id);
}
@RequestMapping("/getById2/{id}")
public User getById2(@PathVariable("id") Integer id){
return userService.selectById(id);
}
}
8.启动类
package com;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@MapperScan("com.dao")
@ComponentScan(basePackages = "com" )
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}