1.簡介
Spring Boot是一款快速開發Web應用程式的架構,MyBatis是一款資料庫通路架構,MySQL是一款開源關系型資料庫。本文将介紹如何在Spring Boot中整合MyBatis并內建MySQL,實作基本的資料增删改查功能。
2.環境搭建
本文的環境為:JDK1.8,Spring Boot2.2.4.RELEASE,Mybatis3.5.6,MySQL8.0.21。
在開發過程中需要內建相關依賴,可以通過Maven或者Gradle等工具進行建構。
3.Spring Boot整合Mybatis
在項目中引入Mybatis,隻需在pom.xml中添加如下依賴即可:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
4.配置MySQL資料庫
在src/main/resources目錄下添加application.properties檔案,進行MySQL的相關配置,如下:
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
以上配置中,url為MySQL資料庫連接配接位址,需要根據實際情況進行修改;username和password為MySQL登入賬号和密碼;driver-class-name為MySQL資料庫驅動。
5.實作資料增删改查
(1)建立實體類User
public class User {
private Long id;
private String name;
private String password;
//getter and setter method
}
(2)建立Mapper接口
@Mapper
public interface UserMapper {
@Insert("INSERT INTO user(name, password) VALUES(#{name}, #{password})")
int insert(User user);
@Delete("DELETE FROM user WHERE id=#{id}")
int deleteById(Long id);
@Update("UPDATE user SET name=#{name}, password=#{password} WHERE id=#{id}")
int update(User user);
@Select("SELECT * FROM user WHERE id=#{id}")
User findById(Long id);
@Select("SELECT * FROM user")
List<User> findAll();
}
(3)建立Service服務
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int insert(User user) {
return userMapper.insert(user);
}
public int deleteById(Long id) {
return userMapper.deleteById(id);
}
public int update(User user) {
return userMapper.update(user);
}
public User findById(Long id) {
return userMapper.findById(id);
}
public List<User> findAll() {
return userMapper.findAll();
}
}
(4)建立Controller控制器
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("")
public int insert(User user) {
return userService.insert(user);
}
@DeleteMapping("/{id}")
public int deleteById(@PathVariable Long id) {
return userService.deleteById(id);
}
@PutMapping("")
public int update(User user) {
return userService.update(user);
}
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
@GetMapping("")
public List<User> findAll() {
return userService.findAll();
}
}
6.結束語
通過以上實作,我們已經成功整合Spring Boot和Mybatis,并成功內建MySQL資料庫,實作了基本的資料增删改查功能。本文隻是一個demo,實際開發中還需考慮更多的實際情況,例如異常處理等,希望對大家有所幫助。