欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot中使用MyBatis詳細(xì)指南

 更新時間:2025年01月03日 08:52:06   作者:顏淡慕瀟  
MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射,將 Spring Boot 和 MyBatis 集成,能夠充分發(fā)揮 Spring Boot 的快速開發(fā)特性和 MyBatis 靈活的數(shù)據(jù)庫操作能力,本文給大家介紹了SpringBoot使用MyBatis詳細(xì)指南,需要的朋友可以參考下

一、基礎(chǔ)介紹

1.1 MyBatis

MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis 可以使用簡單的 XML 或注解來配置和映射原生信息,將接口和 Java 的 POJO(Plain Old Java Objects)映射成數(shù)據(jù)庫中的記錄。

1.2 Spring Boot 集成 MyBatis 的優(yōu)勢

將 Spring Boot 和 MyBatis 集成,能夠充分發(fā)揮 Spring Boot 的快速開發(fā)特性和 MyBatis 靈活的數(shù)據(jù)庫操作能力。通過這種集成,可以快速搭建一個穩(wěn)定、高效的數(shù)據(jù)庫訪問層,簡化開發(fā)流程,提高開發(fā)效率。

二、集成步驟

2.1 創(chuàng)建 Spring Boot 項目

可以使用 Spring Initializr(https://start.spring.io/)來快速創(chuàng)建一個 Spring Boot 項目。在創(chuàng)建項目時,需要選擇以下依賴:

  • Spring Web
  • Spring Data JPA
  • MySQL Driver
  • MyBatis Framework

2.2 配置數(shù)據(jù)源

在 application.properties 文件中配置數(shù)據(jù)庫連接信息:

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 配置實體類的包名,這樣在 MyBatis 映射文件中就可以直接使用實體類名而無需寫全限定名。

2.4 創(chuàng)建實體類

創(chuàng)建一個 Java 實體類,用于映射數(shù)據(jù)庫表中的記錄。例如,創(chuàng)建一個 User 實體類:

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)建一個 Mapper 接口,用于定義數(shù)據(jù)庫操作方法。例如,創(chuàng)建一個 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)建一個 UserMapper.xml 文件,用于實現(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 屬性指定要實現(xiàn)的方法名,resultType 屬性指定返回結(jié)果的類型。

2.7 創(chuàng)建 Service 層

創(chuàng)建一個 Service 層,用于調(diào)用 Mapper 接口中的方法。例如,創(chuàng)建一個 UserService 接口和其實現(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)建一個 Controller 層,用于處理客戶端請求。例如,創(chuàng)建一個 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)表示層級關(guān)系。例如,spring 和 mybatis 是頂級配置項,datasource 是 spring 的子配置項,url、username、password 和 driver-class-name 是 datasource 的子配置項。
  • 冒號后面需要跟一個空格,然后再寫具體的值。

完整項目示例

以下是基于上述 application.yml 配置的完整項目示例,包括之前提到的各個部分:

項目結(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>

實體類(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);
    }
}

測試(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 項目中使用 application.yml 配置文件來集成 MyBatis,并實現(xiàn)完整的用戶管理功能。

以上就是SpringBoot中使用MyBatis詳細(xì)指南的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot使用MyBatis的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • SpringBoot整合chatGPT的項目實踐

    SpringBoot整合chatGPT的項目實踐

    本文主要介紹了SpringBoot整合chatGPT的項目實踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • Java中的HashMap內(nèi)存泄漏問題詳解

    Java中的HashMap內(nèi)存泄漏問題詳解

    這篇文章主要介紹了Java中的HashMap內(nèi)存泄漏問題詳解,WeakHashMap中的key是弱引用,如果再使用之后沒有及時remove掉這個key,那么當(dāng)GC時key就可能會被回收,導(dǎo)致key對應(yīng)的value對象占用的內(nèi)存無法回收進(jìn)而導(dǎo)致內(nèi)存泄漏,需要的朋友可以參考下
    2023-09-09
  • Spring Boot詳解配置文件有哪些作用與細(xì)則

    Spring Boot詳解配置文件有哪些作用與細(xì)則

    SpringBoot項目是一個標(biāo)準(zhǔn)的Maven項目,它的配置文件需要放在src/main/resources/下,其文件名必須為application,其存在兩種文件形式,分別是properties和yaml(或者yml)文件
    2022-07-07
  • Java哈希表的概念及實現(xiàn)完整代碼

    Java哈希表的概念及實現(xiàn)完整代碼

    這篇文章主要介紹了Java哈希表的概念及實現(xiàn)的相關(guān)資料,哈希表是一種高效查找數(shù)據(jù)的結(jié)構(gòu),通過哈希函數(shù)將關(guān)鍵字映射到數(shù)組的索引位置,當(dāng)發(fā)生沖突時,可以通過閉散列或開散列(鏈地址法)來解決,需要的朋友可以參考下
    2024-11-11
  • Java實現(xiàn)雪花算法(snowflake)

    Java實現(xiàn)雪花算法(snowflake)

    這篇文章主要介紹了Java實現(xiàn)雪花算法(snowflake),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • java向mysql插入數(shù)據(jù)亂碼問題的解決方法

    java向mysql插入數(shù)據(jù)亂碼問題的解決方法

    這篇文章主要為大家詳細(xì)介紹了java向mysql插入數(shù)據(jù)亂碼問題的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • idea設(shè)置JVM運行參數(shù)的幾種方式

    idea設(shè)置JVM運行參數(shù)的幾種方式

    對JVM運行參數(shù)進(jìn)行修改是JVM性能調(diào)優(yōu)的重要手段,本文主要介紹了idea設(shè)置JVM運行參數(shù)的幾種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • Springboot2 session設(shè)置超時時間無效的解決

    Springboot2 session設(shè)置超時時間無效的解決

    這篇文章主要介紹了Springboot2 session設(shè)置超時時間無效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • SpringBoot中YAML語法及幾個注意點說明

    SpringBoot中YAML語法及幾個注意點說明

    這篇文章主要介紹了SpringBoot中YAML語法及幾個注意點說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • Spring中Eureka的服務(wù)下線詳解

    Spring中Eureka的服務(wù)下線詳解

    這篇文章主要介紹了Spring中Eureka的服務(wù)下線詳解,根據(jù)默認(rèn)的策略,如果在一定的時間內(nèi),客戶端沒有向注冊中心發(fā)送續(xù)約請求,那么注冊中心就會將該實例從注冊中心移除,需要的朋友可以參考下
    2023-11-11

最新評論