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

springboot數(shù)據(jù)訪問和數(shù)據(jù)視圖的使用方式詳解

 更新時間:2023年06月14日 11:50:53   作者:劉鳳貴  
這篇文章主要為大家介紹了springboot數(shù)據(jù)訪問和數(shù)據(jù)視圖的使用方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

正文

當(dāng)使用 Spring Boot 進(jìn)行數(shù)據(jù)訪問時,我們可以選擇使用 MyBatis 或 JPA(Java Persistence API)來實現(xiàn)增刪改查操作。下面我將分別給出使用這兩種方式整合數(shù)據(jù)訪問的詳細(xì)步驟和示例,同時結(jié)合 Thymeleaf 實現(xiàn)數(shù)據(jù)展現(xiàn)。

方式一: 使用 MyBatis 進(jìn)行數(shù)據(jù)訪問

步驟 1: 創(chuàng)建 Spring Boot 項目

首先,我們需要創(chuàng)建一個 Spring Boot 項目。您可以使用 Spring Initializr(https://start.spring.io/)創(chuàng)建一個新的項目,選擇所需的依賴項和構(gòu)建工具(如 Maven 或 Gradle)。

步驟 2: 添加依賴項

在項目的 pom.xml 文件中,添加 MyBatis 和相關(guān)的依賴項:

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    <!-- H2 Database (可選,用于示例) -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

步驟 3: 創(chuàng)建數(shù)據(jù)庫和模擬數(shù)據(jù)

在此示例中,我們將使用 H2 數(shù)據(jù)庫,并創(chuàng)建一個 users 表來存儲用戶數(shù)據(jù)。在 src/main/resources 目錄下創(chuàng)建一個名為 schema.sql 的文件,并添加以下內(nèi)容:

CREATE TABLE users (
    id bigint AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100)
);
INSERT INTO users (id, name, email) VALUES (1, 'Alice', 'alice@example.com');
INSERT INTO users (id, name, email) VALUES (2, 'Bob', 'bob@example.com');

這將創(chuàng)建一個名為 users 的表,并插入兩條模擬數(shù)據(jù)。

并在application.properties中添加數(shù)據(jù)源的配置信息:

spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

步驟 4: 創(chuàng)建實體類和 MyBatis 映射接口

在 src/main/java 目錄下的domain包下創(chuàng)建一個名為 User.java 的實體類,表示用戶對象,代碼如下:

public class User {
    private Long id;
    private String name;
    private String email;
    // Getters and setters
}

我們可以在dao包下面創(chuàng)建一個名為 UserMapper.java 的接口,定義 MyBatis 的映射方法,代碼如下:

import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
    @Select("SELECT * FROM users")
    List<User> findAll();
    @Select("SELECT * FROM users WHERE id = #{id}")
    User findById(@Param("id") Long id);
    @Insert("INSERT INTO users( name, email) VALUES ( #{name}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void save(User user);
    @Update("UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}")
    void update(User user);
    @Delete("DELETE FROM users WHERE id = #{id}")
    void deleteById(@Param("id") Long id);
}

這里使用了 MyBatis 的注解方式進(jìn)行 SQL 映射。

步驟 5: 創(chuàng)建服務(wù)類和控制器類

在service包下創(chuàng)建一個名為 UserService.java 的服務(wù)類,用于處理用戶數(shù)據(jù)的增刪改查操作,代碼如下:

@Service
public class UserService {
    @Autowired
    private final UserMapper userMapper;
    public List<User> findAll() {
        return userMapper.findAll();
    }
    public User findById(Long id) {
        return userMapper.findById(id);
    }
    public void save(User user) {
        userMapper.save(user);
    }
    public void update(User user) {
        userMapper.update(user);
    }
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }
}

接下來,創(chuàng)建一個名為 UserController.java 的控制器類,用于處理用戶相關(guān)的 HTTP 請求,代碼如下:

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/")
    public String index(Model model) {
        List<User> users = userService.findAll();
        model.addAttribute("users", users);
        return "index";
    }
    @GetMapping("/user/{id}")
    public String getUser(@PathVariable Long id, Model model) {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "user";
    }
    @GetMapping("/user/create")
    public String createUserForm(Model model) {
        model.addAttribute("user", new User());
        return "create_user";
    }
    @PostMapping("/user/create")
    public String createUser(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/";
    }
    @GetMapping("/user/edit/{id}")
    public String editUserForm(@PathVariable Long id, Model model) {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "edit_user";
    }
    @PostMapping("/user/edit/{id}")
    public String editUser(@PathVariable Long id, @ModelAttribute User user) {
        user.setId(id);
        userService.update(user);
        return "redirect:/";
    }
    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.deleteById(id);
        return "redirect:/";
    }
}

步驟 6: 創(chuàng)建 Thymeleaf 模板

在 src/main/resources/templates 目錄下創(chuàng)建以下 Thymeleaf 模板文件:

  • index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用戶列表</title>
</head>
<body>
    <h1>用戶列表</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>操作</th>
        </tr>
        <tr th:each="user : ${users}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.name}"></td>
            <td th:text="${user.email}"></td>
            <td>
                <a th:href="@{/user/{id}(id=${user.id})}" rel="external nofollow" >查看</a>
                <a th:href="@{/user/edit/{id}(id=${user.id})
}">編輯</a>
                <a th:href="@{/user/delete/{id}(id=${user.id})}" rel="external nofollow" >刪除</a>
            </td>
        </tr>
    </table>
    <a th:href="@{/user/create}" rel="external nofollow" >新增</a>
</body>
</html>
  • user.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>查看用戶</title>
</head>
<body>
    <h1>用戶信息</h1>
    <p>ID: <span th:text="${user.id}"></span></p>
    <p>Name: <span th:text="${user.name}"></span></p>
    <p>Email: <span th:text="${user.email}"></span></p>
    <a th:href="@{/}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >返回</a>
</body>
</html>
  • create_user.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>創(chuàng)建用戶</title>
</head>
<body>
    <h1>創(chuàng)建用戶</h1>
    <form th:action="@{/user/create}" th:object="${user}" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" th:field="*{name}">
        <br>
        <label for="email">Email:</label>
        <input type="text" id="email" th:field="*{email}">
        <br>
        <input type="submit" value="Create">
    </form>
    <a th:href="@{/}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >Back</a>
</body>
</html>
  • edit_user.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>編輯用戶</title>
</head>
<body>
    <h1>編輯用戶</h1>
    <form th:action="@{/user/edit/{id}(id=${user.id})}" th:object="${user}" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" th:field="*{name}">
        <br>
        <label for="email">Email:</label>
        <input type="text" id="email" th:field="*{email}">
        <br>
        <input type="submit" value="Update">
    </form>
    <a th:href="@{/}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >返回</a>
</body>
</html>

步驟 7: 運行和測試

現(xiàn)在,您可以運行該應(yīng)用程序,并訪問 http://localhost:8080 查看用戶列表。您可以通過點擊“查看”、“編輯”和“刪除”鏈接來查看、編輯和刪除用戶。

列表頁示例如下:

方式二: 使用 JPA 進(jìn)行數(shù)據(jù)訪問

需要在pom.xml中添加相應(yīng)的依賴如下:

  • pom.xml
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
  • 在repository包,創(chuàng)建一個名為 UserRepository.java 的接口,繼承自 JpaRepository,代碼如下:

UserRepository.java

import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
  • 在涉及到的實體對象中要添加相應(yīng)的配置 @Entity , @Id, @GeneratedValue,代碼如下:

User.java

@Entity(name = "users")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  • 然后在service的服務(wù)類中注入這個 UserRepository,調(diào)用這個bean來進(jìn)行對數(shù)據(jù)的操作就可以,參考如下:

UserService.java

@Autowired
  private UserRepository userRepository;
  • 其他的代碼信息與上一個方式一樣的。

同學(xué)們可以參考這些步驟和示例來理解并掌握 Spring Boot 數(shù)據(jù)訪問的基本操作和 Thymeleaf 的語法,要掌握,重中之重在于多動手練習(xí)。

以上就是springboot的數(shù)據(jù)訪問和數(shù)據(jù)視圖的詳細(xì)內(nèi)容,更多關(guān)于springboot數(shù)據(jù)訪問視圖的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • SpringMVC靜態(tài)資源訪問問題如何解決

    SpringMVC靜態(tài)資源訪問問題如何解決

    這篇文章主要介紹了SpringMVC靜態(tài)資源訪問問題如何解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-11-11
  • Java中Long類型傳入前端數(shù)值出錯問題

    Java中Long類型傳入前端數(shù)值出錯問題

    這篇文章主要介紹了Java中Long類型傳入前端數(shù)值出錯問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • Spring超詳細(xì)講解事務(wù)和事務(wù)傳播機制

    Spring超詳細(xì)講解事務(wù)和事務(wù)傳播機制

    Spring事務(wù)的本質(zhì)就是對數(shù)據(jù)庫事務(wù)的支持,沒有數(shù)據(jù)庫事務(wù),Spring是無法提供事務(wù)功能的。Spring只提供統(tǒng)一的事務(wù)管理接口,具體實現(xiàn)都是由數(shù)據(jù)庫自己實現(xiàn)的,Spring會在事務(wù)開始時,根據(jù)當(dāng)前設(shè)置的隔離級別,調(diào)整數(shù)據(jù)庫的隔離級別,由此保持一致
    2022-06-06
  • Quarkus云原生開篇java框架簡介

    Quarkus云原生開篇java框架簡介

    Quarkus?是小紅帽開源的專門針對云容器環(huán)境優(yōu)化的云原生java框架,博主接下來的項目估計都會使用這個框架來開發(fā),相關(guān)的問題都會記錄在這個系列,本文是個開篇
    2022-02-02
  • Java詳細(xì)講解異常Exception的處理

    Java詳細(xì)講解異常Exception的處理

    異常就是不正常,比如當(dāng)我們身體出現(xiàn)了異常我們會根據(jù)身體情況選擇喝開水、吃藥、看病、等?異常處理方法。?java異常處理機制是我們java語言使用異常處理機制為程序提供了錯誤處理的能力,程序出現(xiàn)的錯誤,程序可以安全的退出,以保證程序正常的運行等
    2022-06-06
  • SpringBoot加載讀取配置文件過程詳細(xì)分析

    SpringBoot加載讀取配置文件過程詳細(xì)分析

    在實際的項目開發(fā)過程中,我們經(jīng)常需要將某些變量從代碼里面抽離出來,放在配置文件里面,以便更加統(tǒng)一、靈活的管理服務(wù)配置信息。所以本文將為大家總結(jié)一下SpringBoot加載配置文件的常用方式,需要的可以參考一下
    2023-01-01
  • IntelliJ IDEA2019實現(xiàn)Web項目創(chuàng)建示例

    IntelliJ IDEA2019實現(xiàn)Web項目創(chuàng)建示例

    這篇文章主要介紹了IntelliJ IDEA2019實現(xiàn)Web項目創(chuàng)建示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • Java 進(jìn)行時間處理的步驟

    Java 進(jìn)行時間處理的步驟

    時間處理是常見的需求,本文將講述Java語言如何進(jìn)行時間處理,感興趣的朋友可以了解下
    2021-05-05
  • java日志打印的完全使用指南

    java日志打印的完全使用指南

    日志就是記錄程序的運行軌跡,方便查找關(guān)鍵信息,也方便快速定位解決問題,下面這篇文章主要給大家介紹了關(guān)于java日志打印使用的相關(guān)資料,需要的朋友可以參考下
    2022-01-01
  • java判讀數(shù)組中是否有重復(fù)值的示例

    java判讀數(shù)組中是否有重復(fù)值的示例

    這篇文章主要介紹了java判讀數(shù)組中是否有重復(fù)值的示例,需要的朋友可以參考下
    2014-04-04

最新評論