springboot+Mybatis+mysql示例

https://start.spring.io

新建项目


spring.png

pom.xml 文件增加mysql和mybatis配置

        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.0
        

删除application.properties,使用yml配置
新增
application-dev.yml、application.ym 文件

dev文件中jdbc:mysql://localhost:3306/ 后跟的是数据库名称

数据中新增user表,并且插入数据

CREATE TABLE `user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES ('1', 'malone', '007');
INSERT INTO `user` VALUES ('2', 'oyl', '520');

新建User类

public class User {
    private Integer id;
    private String username;
    private String password;
    ...省略get set 
}

新建UserMapper

@Repository
public interface UserMapper {
    User getUser(int id);
}

新建UserService

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    public User getUser(int id){
        return userMapper.getUser(id);
    }
}

新建UserController

@RestController
@RequestMapping("/springboot")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("getUser/{id}")
    public String GetUser(@PathVariable int id){
        return userService.getUser(id).toString();
    }
}

resources目录下新增mapping文件夹,并且新建UserMapper.xml





    
        
        
        
    

    


启动类Application,新增

@MapperScan("com.joy.mapper") 

浏览器输入访问地址:http://localhost:8080/springboot/getUser/1 即可成功运行。

项目地址:https://github.com/Malone1023/springboot_mybatis

你可能感兴趣的:(springboot+Mybatis+mysql示例)