1.SpringBoot整合Mybatis
- File| New|Project |Spring Initializr|
- 选择需要的组件:
- 配置Maven:
- 修改配置文件
application.yml
spring:
profiles:
active: dev
application.yml-dev
server:
port: 8080
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
# 让mybatis自动扫描到自定义POJO
type-aliases-package: com.example.pojo
- test数据库建立user表并添加数据测试:
id int 20 primarykey
name varchar 20
- 在com.example下建立pojo、mapper、service、controller包
pojo->User.java
package com.example.pojo;
public class User {
int id;
String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
mapper->UserMapper.java
package com.example.mapper;
import com.example.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
@Select("select * from user where id=#{id}")
User getUserById(@Param("id") int id);
}
service->UserService.java
package com.example.service;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id){
return userMapper.getUserById(id);
}
}
controller->UserController.java
package com.example.controller;
import com.example.pojo.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("get/{id}")
public User getUserById(@PathVariable int id){ return this.userService.getUserById(id);}
}
- 编写启动类:Springbootdemo1Application.java
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//扫描mapper
@MapperScan("com.example.mapper")
public class Springbootdemo1Application {
public static void main(String[] args) {
SpringApplication.run(Springbootdemo1Application.class, args);
}
}
此时,启动服务器,访问
http://localhost:8080/user/get/1
结果如下:
关于SpringBoot整合Mybatis的其他方法后面会继续补充。