springboot數(shù)據(jù)訪問(wèn)和數(shù)據(jù)視圖的使用方式詳解
正文
當(dāng)使用 Spring Boot 進(jìn)行數(shù)據(jù)訪問(wèn)時(shí),我們可以選擇使用 MyBatis 或 JPA(Java Persistence API)來(lái)實(shí)現(xiàn)增刪改查操作。下面我將分別給出使用這兩種方式整合數(shù)據(jù)訪問(wèn)的詳細(xì)步驟和示例,同時(shí)結(jié)合 Thymeleaf 實(shí)現(xiàn)數(shù)據(jù)展現(xiàn)。
方式一: 使用 MyBatis 進(jìn)行數(shù)據(jù)訪問(wèn)
步驟 1: 創(chuàng)建 Spring Boot 項(xiàng)目
首先,我們需要?jiǎng)?chuàng)建一個(gè) Spring Boot 項(xiàng)目。您可以使用 Spring Initializr(https://start.spring.io/)創(chuàng)建一個(gè)新的項(xiàng)目,選擇所需的依賴項(xiàng)和構(gòu)建工具(如 Maven 或 Gradle)。
步驟 2: 添加依賴項(xiàng)
在項(xiàng)目的 pom.xml
文件中,添加 MyBatis 和相關(guān)的依賴項(xiàng):
<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ù)庫(kù)和模擬數(shù)據(jù)
在此示例中,我們將使用 H2 數(shù)據(jù)庫(kù),并創(chuàng)建一個(gè) users
表來(lái)存儲(chǔ)用戶數(shù)據(jù)。在 src/main/resources
目錄下創(chuàng)建一個(gè)名為 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)建一個(gè)名為 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)建實(shí)體類和 MyBatis 映射接口
在 src/main/java
目錄下的domain包下創(chuàng)建一個(gè)名為 User.java
的實(shí)體類,表示用戶對(duì)象,代碼如下:
public class User { private Long id; private String name; private String email; // Getters and setters }
我們可以在dao包下面創(chuàng)建一個(gè)名為 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)建一個(gè)名為 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); } }
接下來(lái),創(chuàng)建一個(gè)名為 UserController.java
的控制器類,用于處理用戶相關(guān)的 HTTP 請(qǐng)求,代碼如下:
@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)行和測(cè)試
現(xiàn)在,您可以運(yùn)行該應(yīng)用程序,并訪問(wèn) http://localhost:8080
查看用戶列表。您可以通過(guò)點(diǎn)擊“查看”、“編輯”和“刪除”鏈接來(lái)查看、編輯和刪除用戶。
列表頁(yè)示例如下:
方式二: 使用 JPA 進(jìn)行數(shù)據(jù)訪問(wèn)
需要在pom.xml中添加相應(yīng)的依賴如下:
- pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
- 在repository包,創(chuàng)建一個(gè)名為
UserRepository.java
的接口,繼承自JpaRepository
,代碼如下:
UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { }
- 在涉及到的實(shí)體對(duì)象中要添加相應(yīng)的配置 @Entity , @Id, @GeneratedValue,代碼如下:
User.java
@Entity(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
- 然后在service的服務(wù)類中注入這個(gè) UserRepository,調(diào)用這個(gè)bean來(lái)進(jìn)行對(duì)數(shù)據(jù)的操作就可以,參考如下:
UserService.java
@Autowired private UserRepository userRepository;
- 其他的代碼信息與上一個(gè)方式一樣的。
同學(xué)們可以參考這些步驟和示例來(lái)理解并掌握 Spring Boot 數(shù)據(jù)訪問(wèn)的基本操作和 Thymeleaf 的語(yǔ)法,要掌握,重中之重在于多動(dòng)手練習(xí)。
以上就是springboot的數(shù)據(jù)訪問(wèn)和數(shù)據(jù)視圖的詳細(xì)內(nèi)容,更多關(guān)于springboot數(shù)據(jù)訪問(wèn)視圖的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot對(duì)數(shù)據(jù)訪問(wèn)層進(jìn)行單元測(cè)試的方法詳解
- 基于Springboot+Mybatis對(duì)數(shù)據(jù)訪問(wèn)層進(jìn)行單元測(cè)試的方式分享
- SpringBoot實(shí)戰(zhàn)記錄之?dāng)?shù)據(jù)訪問(wèn)
- 深入了解Springboot核心知識(shí)點(diǎn)之?dāng)?shù)據(jù)訪問(wèn)配置
- SpringBoot中Mybatis + Druid 數(shù)據(jù)訪問(wèn)的詳細(xì)過(guò)程
- SpringBoot數(shù)據(jù)訪問(wèn)自定義使用Druid數(shù)據(jù)源的方法
- SpringBoot+MyBatis簡(jiǎn)單數(shù)據(jù)訪問(wèn)應(yīng)用的實(shí)例代碼
- SpringBoot數(shù)據(jù)訪問(wèn)的實(shí)現(xiàn)
相關(guān)文章
SpringMVC靜態(tài)資源訪問(wèn)問(wèn)題如何解決
這篇文章主要介紹了SpringMVC靜態(tài)資源訪問(wèn)問(wèn)題如何解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Java中Long類型傳入前端數(shù)值出錯(cuò)問(wèn)題
這篇文章主要介紹了Java中Long類型傳入前端數(shù)值出錯(cuò)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04Spring超詳細(xì)講解事務(wù)和事務(wù)傳播機(jī)制
Spring事務(wù)的本質(zhì)就是對(duì)數(shù)據(jù)庫(kù)事務(wù)的支持,沒(méi)有數(shù)據(jù)庫(kù)事務(wù),Spring是無(wú)法提供事務(wù)功能的。Spring只提供統(tǒng)一的事務(wù)管理接口,具體實(shí)現(xiàn)都是由數(shù)據(jù)庫(kù)自己實(shí)現(xiàn)的,Spring會(huì)在事務(wù)開(kāi)始時(shí),根據(jù)當(dāng)前設(shè)置的隔離級(jí)別,調(diào)整數(shù)據(jù)庫(kù)的隔離級(jí)別,由此保持一致2022-06-06Quarkus云原生開(kāi)篇java框架簡(jiǎn)介
Quarkus?是小紅帽開(kāi)源的專門針對(duì)云容器環(huán)境優(yōu)化的云原生java框架,博主接下來(lái)的項(xiàng)目估計(jì)都會(huì)使用這個(gè)框架來(lái)開(kāi)發(fā),相關(guān)的問(wèn)題都會(huì)記錄在這個(gè)系列,本文是個(gè)開(kāi)篇2022-02-02SpringBoot加載讀取配置文件過(guò)程詳細(xì)分析
在實(shí)際的項(xiàng)目開(kāi)發(fā)過(guò)程中,我們經(jīng)常需要將某些變量從代碼里面抽離出來(lái),放在配置文件里面,以便更加統(tǒng)一、靈活的管理服務(wù)配置信息。所以本文將為大家總結(jié)一下SpringBoot加載配置文件的常用方式,需要的可以參考一下2023-01-01IntelliJ IDEA2019實(shí)現(xiàn)Web項(xiàng)目創(chuàng)建示例
這篇文章主要介紹了IntelliJ IDEA2019實(shí)現(xiàn)Web項(xiàng)目創(chuàng)建示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04