您好,登录后才能下订单哦!
在现代Web应用开发中,SpringBoot因其简洁的配置和强大的功能而备受开发者青睐。Mybatis优秀的持久层框架,能够简化数据库操作。Thymeleaf则是一个现代化的服务器端Java模板引擎,适用于Web和独立环境。本文将详细介绍如何在SpringBoot项目中整合Mybatis与Thymeleaf,并实现基本的增删改查(CRUD)功能。
在开始之前,确保你的开发环境中已经安装了以下工具:
首先,我们需要创建一个SpringBoot项目。可以通过Spring Initializr来快速生成项目骨架。
在application.properties
文件中配置MySQL数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
在application.properties
中添加Mybatis相关配置:
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.springbootmybatisthymeleaf.entity
在src/main/java/com/example/springbootmybatisthymeleaf/entity
目录下创建实体类User.java
:
package com.example.springbootmybatisthymeleaf.entity;
public class User {
private Long id;
private String name;
private Integer age;
private String email;
// Getters and Setters
}
在src/main/java/com/example/springbootmybatisthymeleaf/mapper
目录下创建Mapper接口UserMapper.java
:
package com.example.springbootmybatisthymeleaf.mapper;
import com.example.springbootmybatisthymeleaf.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(name, age, email) VALUES(#{name}, #{age}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insert(User user);
@Update("UPDATE user SET name=#{name}, age=#{age}, email=#{email} WHERE id=#{id}")
void update(User user);
@Delete("DELETE FROM user WHERE id=#{id}")
void delete(Long id);
}
在src/main/resources/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.springbootmybatisthymeleaf.mapper.UserMapper">
<select id="findAll" resultType="User">
SELECT * FROM user
</select>
<select id="findById" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insert" parameterType="User">
INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})
</insert>
<update id="update" parameterType="User">
UPDATE user SET name=#{name}, age=#{age}, email=#{email} WHERE id=#{id}
</update>
<delete id="delete">
DELETE FROM user WHERE id=#{id}
</delete>
</mapper>
在application.properties
中添加Thymeleaf相关配置:
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
在src/main/resources/templates
目录下创建Thymeleaf模板文件index.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Actions</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
<td th:text="${user.email}"></td>
<td>
<a th:href="@{/edit/{id}(id=${user.id})}">Edit</a>
<a th:href="@{/delete/{id}(id=${user.id})}">Delete</a>
</td>
</tr>
</table>
<a th:href="@{/add}">Add New User</a>
</body>
</html>
在src/main/java/com/example/springbootmybatisthymeleaf/service
目录下创建UserService.java
接口:
package com.example.springbootmybatisthymeleaf.service;
import com.example.springbootmybatisthymeleaf.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);
}
在src/main/java/com/example/springbootmybatisthymeleaf/service/impl
目录下创建UserServiceImpl.java
实现类:
package com.example.springbootmybatisthymeleaf.service.impl;
import com.example.springbootmybatisthymeleaf.entity.User;
import com.example.springbootmybatisthymeleaf.mapper.UserMapper;
import com.example.springbootmybatisthymeleaf.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.insert(user);
}
@Override
public void update(User user) {
userMapper.update(user);
}
@Override
public void delete(Long id) {
userMapper.delete(id);
}
}
在src/main/java/com/example/springbootmybatisthymeleaf/controller
目录下创建UserController.java
:
package com.example.springbootmybatisthymeleaf.controller;
import com.example.springbootmybatisthymeleaf.entity.User;
import com.example.springbootmybatisthymeleaf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public String listUsers(Model model) {
model.addAttribute("users", userService.findAll());
return "index";
}
@GetMapping("/add")
public String showAddForm(Model model) {
model.addAttribute("user", new User());
return "add-user";
}
@PostMapping("/add")
public String addUser(@ModelAttribute User user) {
userService.save(user);
return "redirect:/users";
}
@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable Long id, Model model) {
model.addAttribute("user", userService.findById(id));
return "edit-user";
}
@PostMapping("/edit/{id}")
public String updateUser(@PathVariable Long id, @ModelAttribute User user) {
user.setId(id);
userService.update(user);
return "redirect:/users";
}
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable Long id) {
userService.delete(id);
return "redirect:/users";
}
}
在src/main/resources/templates
目录下创建add-user.html
和edit-user.html
模板文件。
add-user.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Add User</title>
</head>
<body>
<h1>Add User</h1>
<form th:action="@{/users/add}" th:object="${user}" method="post">
<label for="name">Name:</label>
<input type="text" id="name" th:field="*{name}" required>
<br>
<label for="age">Age:</label>
<input type="number" id="age" th:field="*{age}" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" th:field="*{email}" required>
<br>
<button type="submit">Add User</button>
</form>
<a th:href="@{/users}">Back to List</a>
</body>
</html>
edit-user.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Edit User</title>
</head>
<body>
<h1>Edit User</h1>
<form th:action="@{/users/edit/{id}(id=${user.id})}" th:object="${user}" method="post">
<label for="name">Name:</label>
<input type="text" id="name" th:field="*{name}" required>
<br>
<label for="age">Age:</label>
<input type="number" id="age" th:field="*{age}" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" th:field="*{email}" required>
<br>
<button type="submit">Update User</button>
</form>
<a th:href="@{/users}">Back to List</a>
</body>
</html>
springboot_db
的数据库。springboot_db
数据库中创建user
表:CREATE TABLE user (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
email VARCHAR(255) NOT NULL
);
http://localhost:8080/users
,你将看到用户列表页面。通过本文的介绍,我们详细讲解了如何在SpringBoot项目中整合Mybatis与Thymeleaf,并实现了基本的增删改查功能。SpringBoot的简洁配置和Mybatis的强大功能使得数据库操作变得非常简单,而Thymeleaf的模板引擎则使得前端页面的开发更加高效。希望本文能帮助你快速上手SpringBoot、Mybatis和Thymeleaf的整合开发。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。