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: 運行和測試
現(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)文章!
- SpringBoot對數(shù)據(jù)訪問層進(jìn)行單元測試的方法詳解
- 基于Springboot+Mybatis對數(shù)據(jù)訪問層進(jìn)行單元測試的方式分享
- SpringBoot實戰(zhàn)記錄之?dāng)?shù)據(jù)訪問
- 深入了解Springboot核心知識點之?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)文章
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-06IntelliJ 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