亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

一、基礎(chǔ)介紹

1.1 MyBatis

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

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

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

二、集成步驟

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

可以使用 Spring Initializr(https://start.spring.io/)來(lái)快速創(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í)體類(lèi)的包名,這樣在 MyBatis 映射文件中就可以直接使用實(shí)體類(lèi)名而無(wú)需寫(xiě)全限定名。

2.4 創(chuàng)建實(shí)體類(lèi)

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

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é)果的類(lèi)型。

2.7 創(chuàng)建 Service 層

創(chuàng)建一個(gè) Service 層,用于調(diào)用 Mapper 接口中的方法。例如,創(chuàng)建一個(gè) UserService 接口和其實(shí)現(xiàn)類(lèi) 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

說(shuō)明

  • 在 YAML 中,使用縮進(jìn)表示層級(jí)關(guān)系。例如,spring 和 mybatis 是頂級(jí)配置項(xiàng),datasource 是 spring 的子配置項(xiàng),url、usernamepassword 和 driver-class-name 是 datasource 的子配置項(xiàng)。
  • 冒號(hào)后面需要跟一個(gè)空格,然后再寫(xiě)具體的值。

完整項(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í)體類(lèi)(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()));
    }
}

通過(guò)上述配置和代碼示例,你可以在 Spring Boot 項(xiàng)目中使用 application.yml 配置文件來(lái)集成 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í)踐

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    SpringBoot中YAML語(yǔ)法及幾個(gè)注意點(diǎn)說(shuō)明

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

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

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

最新評(píng)論