springboot數(shù)據(jù)訪問和數(shù)據(jù)視圖的使用方式詳解
正文
當(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: 運(yùn)行和測試
現(xiàn)在,您可以運(yùn)行該應(yīng)用程序,并訪問 http://localhost:8080 查看用戶列表。您可以通過點(diǎn)擊“查看”、“編輯”和“刪除”鏈接來查看、編輯和刪除用戶。
列表頁示例如下:

方式二: 使用 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)文章!
- SpringBoot對數(shù)據(jù)訪問層進(jìn)行單元測試的方法詳解
- 基于Springboot+Mybatis對數(shù)據(jù)訪問層進(jìn)行單元測試的方式分享
- SpringBoot實戰(zhàn)記錄之?dāng)?shù)據(jù)訪問
- 深入了解Springboot核心知識點(diǎn)之?dāng)?shù)據(jù)訪問配置
- SpringBoot中Mybatis + Druid 數(shù)據(jù)訪問的詳細(xì)過程
- SpringBoot數(shù)據(jù)訪問自定義使用Druid數(shù)據(jù)源的方法
- SpringBoot+MyBatis簡單數(shù)據(jù)訪問應(yīng)用的實例代碼
- SpringBoot數(shù)據(jù)訪問的實現(xiàn)
相關(guān)文章
Jmeter壓力測試簡單教程(包括服務(wù)器狀態(tài)監(jiān)控)
Jmeter是一個非常好用的壓力測試工具。Jmeter用來做輕量級的壓力測試,非常合適,本文詳細(xì)的介紹了Jmeter的使用,感性的可以了解一下2021-11-11
根據(jù)URL下載圖片至客戶端、服務(wù)器的簡單實例
下面小編就為大家?guī)硪黄鶕?jù)URL下載圖片至客戶端、服務(wù)器的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12
Java多線程編程中易混淆的3個關(guān)鍵字總結(jié)
這篇文章主要介紹了Java多線程編程中易混淆的3個關(guān)鍵字總結(jié),本文總結(jié)了、volatile、ThreadLocal、synchronized等3個關(guān)鍵字,對這幾個容易混淆概念的關(guān)鍵字分別做了講解,需要的朋友可以參考下2015-03-03
Spring標(biāo)準(zhǔn)的xml文件頭實例分析
這篇文章主要介紹了Spring標(biāo)準(zhǔn)的xml文件頭實例分析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11
詳解Spring如何使用@Scheduled注解執(zhí)行定時任務(wù)
在現(xiàn)代的Java應(yīng)用程序中,定時任務(wù)是一種常見的需求,Spring框架提供了多種方式來管理定時任務(wù),其中??@Scheduled??注解因其簡潔和易用性而受到開發(fā)者的青睞,下面我們就來看看具體實現(xiàn)方法吧2025-08-08

