SpringBoot中使用MyBatis詳細(xì)指南
一、基礎(chǔ)介紹
1.1 MyBatis
MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲(chǔ)過程以及高級(jí)映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis 可以使用簡(jiǎn)單的 XML 或注解來配置和映射原生信息,將接口和 Java 的 POJO(Plain Old Java Objects)映射成數(shù)據(jù)庫(kù)中的記錄。
1.2 Spring Boot 集成 MyBatis 的優(yōu)勢(shì)
將 Spring Boot 和 MyBatis 集成,能夠充分發(fā)揮 Spring Boot 的快速開發(fā)特性和 MyBatis 靈活的數(shù)據(jù)庫(kù)操作能力。通過這種集成,可以快速搭建一個(gè)穩(wěn)定、高效的數(shù)據(jù)庫(kù)訪問層,簡(jiǎn)化開發(fā)流程,提高開發(fā)效率。
二、集成步驟
2.1 創(chuàng)建 Spring Boot 項(xiàng)目
可以使用 Spring Initializr(https://start.spring.io/)來快速創(chuàng)建一個(gè) Spring Boot 項(xiàng)目。在創(chuàng)建項(xiàng)目時(shí),需要選擇以下依賴:
- Spring Web
- Spring Data JPA
- MySQL Driver
- MyBatis Framework
2.2 配置數(shù)據(jù)源
在 application.properties 文件中配置數(shù)據(jù)庫(kù)連接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/yourdatabase spring.datasource.username=yourusername spring.datasource.password=yourpassword spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2.3 配置 MyBatis
在 application.properties 文件中配置 MyBatis 的相關(guān)屬性:
mybatis.mapper-locations=classpath:/mapper/*.xml mybatis.type-aliases-package=com.example.demo.entity
mybatis.mapper-locations 配置 MyBatis 映射文件的位置,mybatis.type-aliases-package 配置實(shí)體類的包名,這樣在 MyBatis 映射文件中就可以直接使用實(shí)體類名而無需寫全限定名。
2.4 創(chuàng)建實(shí)體類
創(chuàng)建一個(gè) Java 實(shí)體類,用于映射數(shù)據(jù)庫(kù)表中的記錄。例如,創(chuàng)建一個(gè) User 實(shí)體類:
package com.example.demo.entity;
public class User {
private Long id;
private String username;
private String password;
// 省略 getters 和 setters
}
2.5 創(chuàng)建 Mapper 接口
創(chuàng)建一個(gè) Mapper 接口,用于定義數(shù)據(jù)庫(kù)操作方法。例如,創(chuàng)建一個(gè) UserMapper 接口:
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> findAll();
}
@Mapper 注解用于將該接口標(biāo)記為 MyBatis 的 Mapper 接口。
2.6 創(chuàng)建 Mapper 映射文件
在 resources/mapper 目錄下創(chuàng)建一個(gè) UserMapper.xml 文件,用于實(shí)現(xiàn) Mapper 接口中的方法:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="findAll" resultType="com.example.demo.entity.User">
SELECT * FROM user
</select>
</mapper>
namespace 屬性指定 Mapper 接口的全限定名,id 屬性指定要實(shí)現(xiàn)的方法名,resultType 屬性指定返回結(jié)果的類型。
2.7 創(chuàng)建 Service 層
創(chuàng)建一個(gè) Service 層,用于調(diào)用 Mapper 接口中的方法。例如,創(chuàng)建一個(gè) UserService 接口和其實(shí)現(xiàn)類 UserServiceImpl:
package com.example.demo.service;
import com.example.demo.entity.User;
import java.util.List;
public interface UserService {
List<User> findAll();
}
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
}
2.8 創(chuàng)建 Controller 層
創(chuàng)建一個(gè) Controller 層,用于處理客戶端請(qǐng)求。例如,創(chuàng)建一個(gè) UserController:
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> findAll() {
return userService.findAll();
}
}
三、示例完整代碼
1. 創(chuàng)建 application.yml
在 src/main/resources 目錄下創(chuàng)建 application.yml 文件。
2. 配置數(shù)據(jù)源和 MyBatis
將原本 application.properties 中的配置內(nèi)容轉(zhuǎn)換為 YAML 格式,如下:
spring:
datasource:
url: jdbc:mysql://localhost:3306/yourdatabase
username: yourusername
password: yourpassword
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.example.demo.entity
說明
- 在 YAML 中,使用縮進(jìn)表示層級(jí)關(guān)系。例如,
spring和mybatis是頂級(jí)配置項(xiàng),datasource是spring的子配置項(xiàng),url、username、password和driver-class-name是datasource的子配置項(xiàng)。 - 冒號(hào)后面需要跟一個(gè)空格,然后再寫具體的值。
完整項(xiàng)目示例
以下是基于上述 application.yml 配置的完整項(xiàng)目示例,包括之前提到的各個(gè)部分:
項(xiàng)目結(jié)構(gòu)
src
├── main
│ ├── java
│ │ ├── com
│ │ │ ├── example
│ │ │ │ ├── demo
│ │ │ │ │ ├── controller
│ │ │ │ │ │ └── UserController.java
│ │ │ │ │ ├── entity
│ │ │ │ │ │ └── User.java
│ │ │ │ │ ├── mapper
│ │ │ │ │ │ ├── UserMapper.java
│ │ │ │ │ │ └── UserMapper.xml
│ │ │ │ │ ├── service
│ │ │ │ │ │ ├── UserService.java
│ │ │ │ │ │ └── impl
│ │ │ │ │ │ └── UserServiceImpl.java
│ │ │ │ │ └── DemoApplication.java
│ └── resources
│ ├── application.yml
│ └── mapper
│ └── UserMapper.xml
└── test
└── java
└── com
└── example
└── demo
└── DemoApplicationTests.java
依賴配置(pom.xml)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
實(shí)體類(User.java)
package com.example.demo.entity;
public class User {
private Long id;
private String username;
private String password;
// 構(gòu)造函數(shù)
public User() {}
public User(String username, String password) {
this.username = username;
this.password = password;
}
// getters 和 setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Mapper 接口(UserMapper.java)
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> findAll();
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
@Insert("INSERT INTO user (username, password) VALUES (#{username}, #{password})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void save(User user);
@Update("UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}")
void update(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
void delete(Long id);
}
Mapper 映射文件(UserMapper.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="findAll" resultType="com.example.demo.entity.User">
SELECT * FROM user
</select>
<select id="findById" resultType="com.example.demo.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="save" keyProperty="id" useGeneratedKeys="true">
INSERT INTO user (username, password) VALUES (#{username}, #{password})
</insert>
<update id="update">
UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}
</update>
<delete id="delete">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
Service 層
UserService.java
package com.example.demo.service;
import com.example.demo.entity.User;
import java.util.List;
public interface UserService {
List<User> findAll();
User findById(Long id);
void save(User user);
void update(User user);
void delete(Long id);
}
UserServiceImpl.java
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
@Override
public User findById(Long id) {
return userMapper.findById(id);
}
@Override
public void save(User user) {
userMapper.save(user);
}
@Override
public void update(User user) {
userMapper.update(user);
}
@Override
public void delete(Long id) {
userMapper.delete(id);
}
}
Controller 層(UserController.java)
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public ResponseEntity<List<User>> findAll() {
List<User> users = userService.findAll();
return new ResponseEntity<>(users, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<User> findById(@PathVariable Long id) {
User user = userService.findById(id);
if (user!= null) {
return new ResponseEntity<>(user, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@PostMapping
public ResponseEntity<Void> save(@RequestBody User user) {
userService.save(user);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@PutMapping
public ResponseEntity<Void> update(@RequestBody User user) {
userService.update(user);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
userService.delete(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
測(cè)試(DemoApplicationTests.java)
package com.example.demo;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private UserService userService;
@Test
public void testFindAll() {
assertEquals(0, userService.findAll().size());
}
@Test
public void testSaveAndFindById() {
User user = new User("testuser", "testpassword");
userService.save(user);
assertNotNull(userService.findById(user.getId()));
}
@Test
public void testUpdate() {
User user = new User("testuser", "testpassword");
userService.save(user);
user.setPassword("newpassword");
userService.update(user);
assertEquals("newpassword", userService.findById(user.getId()).getPassword());
}
@Test
public void testDelete() {
User user = new User("testuser", "testpassword");
userService.save(user);
userService.delete(user.getId());
assertNull(userService.findById(user.getId()));
}
}
通過上述配置和代碼示例,你可以在 Spring Boot 項(xiàng)目中使用 application.yml 配置文件來集成 MyBatis,并實(shí)現(xiàn)完整的用戶管理功能。
以上就是SpringBoot中使用MyBatis詳細(xì)指南的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot使用MyBatis的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringBoot整合chatGPT的項(xiàng)目實(shí)踐
本文主要介紹了SpringBoot整合chatGPT的項(xiàng)目實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
Java實(shí)現(xiàn)雪花算法(snowflake)
這篇文章主要介紹了Java實(shí)現(xiàn)雪花算法(snowflake),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
java向mysql插入數(shù)據(jù)亂碼問題的解決方法
這篇文章主要為大家詳細(xì)介紹了java向mysql插入數(shù)據(jù)亂碼問題的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09
idea設(shè)置JVM運(yùn)行參數(shù)的幾種方式
對(duì)JVM運(yùn)行參數(shù)進(jìn)行修改是JVM性能調(diào)優(yōu)的重要手段,本文主要介紹了idea設(shè)置JVM運(yùn)行參數(shù)的幾種方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
Springboot2 session設(shè)置超時(shí)時(shí)間無效的解決
這篇文章主要介紹了Springboot2 session設(shè)置超時(shí)時(shí)間無效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
SpringBoot中YAML語(yǔ)法及幾個(gè)注意點(diǎn)說明
這篇文章主要介紹了SpringBoot中YAML語(yǔ)法及幾個(gè)注意點(diǎn)說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02

