springboot对数据库进行增删改查示例代码
时间: 2023-09-11 22:07:24 浏览: 18
以下是一个简单的示例代码,使用Spring Boot框架与MySQL数据库进行增删改查操作:
首先,你需要在`pom.xml`文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
接下来,创建一个实体类`User`,例如:
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String password;
// getters and setters
}
```
然后,创建一个`UserRepository`接口来管理用户实体:
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
```
在这个接口中,我们使用了Spring Data JPA提供的`JpaRepository`,它提供了很多CRUD操作的默认实现。我们还定义了一个自定义方法`findByEmail()`,用于根据用户的电子邮件地址查询用户。
接下来,编写一个`UserService`类来实现业务逻辑:
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
public List<User> findAll() {
return userRepository.findAll();
}
public User save(User user) {
return userRepository.save(user);
}
public void deleteById(Long id) {
userRepository.deleteById(id);
}
}
```
在这个类中,我们使用了`@Autowired`注解来注入`UserRepository`实例,然后实现了一些基本的增删改查操作,如`findByEmail()`、`findAll()`、`save()`和`deleteById()`。
最后,创建一个`UserController`类来处理HTTP请求:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{email}")
public User findByEmail(@PathVariable String email) {
return userService.findByEmail(email);
}
@GetMapping
public List<User> findAll() {
return userService.findAll();
}
@PostMapping
public User save(@RequestBody User user) {
return userService.save(user);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable Long id) {
userService.deleteById(id);
}
}
```
在这个类中,我们使用了`@RestController`注解来标识这是一个REST控制器,又使用了`@Autowired`注解来注入`UserService`实例,然后实现了一些基本的HTTP请求处理方法,如`findByEmail()`、`findAll()`、`save()`和`deleteById()`。
以上就是一个简单的Spring Boot与MySQL数据库进行增删改查操作的示例代码。
相关推荐





这里提供一个简单的示例,使用Spring Boot和Thymeleaf模板引擎实现网页端的增删改查功能。
首先,创建一个实体类(例如Student),包含需要存储的属性,如id、name、age等。
java
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
// 省略getter和setter
}
接下来,创建一个Repository接口,继承自JpaRepository,用于实现对数据库的增删改查操作。
java
public interface StudentRepository extends JpaRepository<Student, Long> {
}
然后,创建一个控制器类,用于处理请求和响应。在控制器中,注入StudentRepository,用于处理对数据库的操作。
java
@Controller
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@RequestMapping("/")
public String index(Model model) {
List<Student> students = studentRepository.findAll();
model.addAttribute("students", students);
return "index";
}
@GetMapping("/add")
public String addForm(Model model) {
model.addAttribute("student", new Student());
return "add";
}
@PostMapping("/add")
public String addSubmit(@ModelAttribute Student student) {
studentRepository.save(student);
return "redirect:/";
}
@GetMapping("/edit/{id}")
public String editForm(@PathVariable Long id, Model model) {
Student student = studentRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid student Id:" + id));
model.addAttribute("student", student);
return "edit";
}
@PostMapping("/edit/{id}")
public String editSubmit(@PathVariable Long id, @ModelAttribute Student student) {
student.setId(id);
studentRepository.save(student);
return "redirect:/";
}
@GetMapping("/delete/{id}")
public String delete(@PathVariable Long id) {
studentRepository.deleteById(id);
return "redirect:/";
}
}
在控制器中,定义了以下请求处理方法:
- index:用于显示所有学生数据的页面;
- addForm:用于显示添加学生数据的页面;
- addSubmit:用于处理添加学生数据的请求;
- editForm:用于显示修改学生数据的页面;
- editSubmit:用于处理修改学生数据的请求;
- delete:用于处理删除学生数据的请求。
最后,创建Thymeleaf模板,用于显示网页内容。在模板中,使用Thymeleaf提供的语法,实现对控制器中注入的数据进行展示和操作。
例如,index.html模板的代码如下:
html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>学生信息</title>
</head>
<body>
学生信息
编号
姓名
年龄
操作
编辑
删除
添加学生信息
</body>
</html>
以上示例代码中,使用Thymeleaf语法实现了对学生信息进行展示和操作,并且通过控制器中的请求处理方法,实现了对数据库的增删改查操作。
需要注意的是,示例代码中省略了异常处理、表单校验、安全性等方面的处理,实际开发中需要根据具体需求进行实现。












以下是一个简单的Spring Boot实现网页端登录和增删改查的示例代码:
1. 首先,我们需要创建一个用户实体类 User.java:
java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String fullName;
// getters and setters
}
2. 创建一个用户仓库类 UserRepository.java:
java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
3. 创建一个服务类 UserService.java:
java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
public void save(User user) {
userRepository.save(user);
}
public void delete(User user) {
userRepository.delete(user);
}
public List<User> findAll() {
return userRepository.findAll();
}
}
4. 创建一个控制器类 UserController.java:
java
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/")
public String index(Model model) {
model.addAttribute("users", userService.findAll());
return "index";
}
@GetMapping("/login")
public String loginForm() {
return "login";
}
@PostMapping("/login")
public String login(@RequestParam String email, @RequestParam String password, HttpSession session) {
User user = userService.findByEmail(email);
if (user != null && user.getPassword().equals(password)) {
session.setAttribute("user", user);
return "redirect:/";
} else {
return "redirect:/login";
}
}
@GetMapping("/logout")
public String logout(HttpSession session) {
session.removeAttribute("user");
return "redirect:/";
}
@GetMapping("/register")
public String registerForm(Model model) {
model.addAttribute("user", new User());
return "register";
}
@PostMapping("/register")
public String register(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "register";
} else {
userService.save(user);
return "redirect:/login";
}
}
@GetMapping("/edit/{id}")
public String editForm(@PathVariable Long id, Model model) {
User user = userService.findById(id);
if (user != null) {
model.addAttribute("user", user);
return "edit";
} else {
return "redirect:/";
}
}
@PostMapping("/edit")
public String edit(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "edit";
} else {
userService.save(user);
return "redirect:/";
}
}
@GetMapping("/delete/{id}")
public String delete(@PathVariable Long id) {
User user = userService.findById(id);
if (user != null) {
userService.delete(user);
}
return "redirect:/";
}
}
5. 创建网页模板文件 index.html,login.html,register.html,edit.html:
index.html
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Management</title>
</head>
<body>
User Management
Logout
ID
Email
Full Name
Actions
Edit
Delete
Register
</body>
</html>
login.html
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
Login
<form method="post" action="/login">
<label>Email:</label>
<input type="email" name="email">
<label>Password:</label>
<input type="password" name="password">
<input type="submit" value="Login"> </form> Register </body> </html> register.html html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Register</title> </head> <body> Register <form method="post" action="/register"> <label>Email:</label>
<input type="email" name="email" th:field="*{email}">
<label>Password:</label>
<input type="password" name="password" th:field="*{password}">
<label>Full Name:</label>
<input type="text" name="fullName" th:field="*{fullName}">
<input type="submit" value="Register"> </form> Login </body> </html> edit.html html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Edit User</title> </head> <body> Edit User <form method="post" action="/edit"> <input type="hidden" name="id" th:field="*{id}"> <label>Email:</label>
<input type="email" name="email" th:field="*{email}">
<label>Password:</label>
<input type="password" name="password" th:field="*{password}">
<label>Full Name:</label>
<input type="text" name="fullName" th:field="*{fullName}">
<input type="submit" value="Save"> </form> Back to List </body> </html> 6. 最后,在 application.properties 文件中设置数据库连接和端口: spring.datasource.url=jdbc:mysql://localhost:3306/user_management?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root server.port=8080 这样我们就完成了一个简单的Spring Boot实现网页端登录和增删改查的示例代码。
<input type="email" name="email">
<label>Password:</label>
<input type="password" name="password">
<input type="submit" value="Login"> </form> Register </body> </html> register.html html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Register</title> </head> <body> Register <form method="post" action="/register"> <label>Email:</label>
<input type="email" name="email" th:field="*{email}">
<label>Password:</label>
<input type="password" name="password" th:field="*{password}">
<label>Full Name:</label>
<input type="text" name="fullName" th:field="*{fullName}">
<input type="submit" value="Register"> </form> Login </body> </html> edit.html html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Edit User</title> </head> <body> Edit User <form method="post" action="/edit"> <input type="hidden" name="id" th:field="*{id}"> <label>Email:</label>
<input type="email" name="email" th:field="*{email}">
<label>Password:</label>
<input type="password" name="password" th:field="*{password}">
<label>Full Name:</label>
<input type="text" name="fullName" th:field="*{fullName}">
<input type="submit" value="Save"> </form> Back to List </body> </html> 6. 最后,在 application.properties 文件中设置数据库连接和端口: spring.datasource.url=jdbc:mysql://localhost:3306/user_management?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root server.port=8080 这样我们就完成了一个简单的Spring Boot实现网页端登录和增删改查的示例代码。
