目录
(一)连接MySql
(二)创建实体模型
(三)创建Repository接口
(四)创建Controller类
(五)运行AccessingDataMysqlApplication
(六)HTML页面设置
参考SpringBoot官网教程:
1.Validating Form Input
2.Handling Form Submission
3.Accessing data with MySQL
在pom.xml中引入以下依赖:
---------连接数据库----------
mysql
mysql-connector-java
8.0.12
-------用于启用JPA和Hibernate,实现数据的持久化-------
org.springframework.boot
spring-boot-starter-data-jpa
-----------启用web应用程序----------
org.springframework.boot
spring-boot-starter-web
--------用于构建交互的WEB应用程序-------
org.springframework.boot
spring-boot-starter-thymeleaf
-------启用校验功能----------
org.springframework.boot
spring-boot-starter-validation
3.1.5
在application.properties中添加如下代码,连接数据库
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/db_example?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456ab
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true
# spring.thymeleaf.cache=false
# spring.thymeleaf.prefix=classpath:/templates/
# spring.thymeleaf.suffix=.html
也可以添加application.yml:
application.yml 的功能和 application.properties 是一样的,不过因为yml文件是树状结构,写起来有更好的层次感,更易于理解,所以很多人都选择了yml文件。
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456ab
@Entity注解用于将一个类标识为 JPA 实体,它告诉 Hibernate 或其他 JPA 实现框架将这个类映射为数据库中的表
注:想深入学习校验方法及注释的小伙伴可以看看这个:
如何在 Spring/Spring Boot 中优雅地做参数校验?-腾讯云开发者社区-腾讯云 (tencent.com)
package com.example.accessingdatamysql;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.SequenceGenerator;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
@Entity // This tells Hibernate to make a table out of this class
public class User {
@Id
//指定序列生成器,序列生成器的名称为"user_seq"
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
//每次增长值为1
@SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
private Integer id;
@NotNull(message = "姓名不能为空")
@Size(min = 2, max = 30, message = "姓名长度必须在2-30之间")
private String name;
@Email
@NotEmpty(message = "邮箱不能为空")
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString() {
return "User(id:" + this.id + ",name:" + this.name + ",email:" + this.email + ")";
}
}
Repository接口,用于定义数据访问的方法
package com.example.accessingdatamysql;
import org.springframework.data.repository.CrudRepository;
// import com.example.accessingdatamysql.User;
// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
//使用Iterable,可以根据条件来查询匹配的用户,并获取到一个包含所有符合条件的迭代的用户列表。
public interface UserRepository extends CrudRepository {
//根据姓名查询用户
Iterable findByName(String name);
//根据邮箱查询用户
Iterable findByEmail(String email);
//根据邮箱和姓名查询用户
Iterable findByNameAndEmail(String email,String name);
}
Controller类通常用于Web应用程序,它接收用户的HTTP请求,调用业务逻辑处理请求,并返回一个包含响应数据的视图。
package com.example.accessingdatamysql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import jakarta.validation.Valid;
@Controller
@Validated
public class WebController implements WebMvcConfigurer {
@Autowired
private UserRepository userRepository;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
@GetMapping("/form")
public String showForm(Model model) {
model.addAttribute("user", new User());
return "form";
}
@PostMapping("/")
public String submintForm(@Valid @ModelAttribute("user") User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
userRepository.save(user);
return "redirect:/list";
}
@GetMapping("/list")
public String showList(Model model) {
model.addAttribute("userList", userRepository.findAll());
return "list";
}
@GetMapping(path = "/deleteAll")
public String deleteAllUsers(Model model) {
userRepository.deleteAll();
Iterable userList = userRepository.findAll();
model.addAttribute("userList", userList);
return "redirect:/list";
}
@GetMapping(path = "/delete/{id}")
public String deleteUser(@PathVariable("id") Integer id, Model model) {
userRepository.deleteById(id);
Iterable userList = userRepository.findAll();
model.addAttribute("userList", userList);
return "redirect:/list"; // 返回list.html模板
}
@GetMapping(path = "/edit/{id}")
public String updateUser(@PathVariable("id") Integer id, Model model) {
User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user ID"));
model.addAttribute("user", user);
return "edit";
}
@PostMapping(path = "/update")
public String update(@Valid User user, Model model) {
userRepository.save(user);
Iterable userList = userRepository.findAll();
model.addAttribute("userList", userList);
return "list";
}
@GetMapping("/find")
public String findUserByNameAndEmail(@RequestParam("name") String name,
@RequestParam("email") String email, Model model) {
Iterable userlist;
if (!name.isEmpty() && !email.isEmpty()) {
// 根据姓名和邮箱查询用户
userlist = userRepository.findByNameAndEmail(name, email);
} else if (!name.isEmpty()) {
// 根据姓名查询用户
userlist = userRepository.findByName(name);
} else if (!email.isEmpty()) {
// 根据邮箱查询用户
userlist = userRepository.findByEmail(email);
} else {
// 返回所有用户
userlist = userRepository.findAll();
}
model.addAttribute("userlist", userlist);
return "check";
}
}
这里的注释
@Valid:用于验证注释是否符合要求,例如
这里就是检验密码是否为空
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping
public User create (@Valid @RequestBody User user) {
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
user.setId("1");
return user;
}
}
public class User {
private String id;
@NotBlank(message = "密码不能为空")
private String password;
}
@RequestParam:将请求参数绑定到你控制器的方法参数上(是springmvc中接收普通参数的注解)
//url参数中的name必须要和@RequestParam("name")一致
@RequestMapping("show16")
public ModelAndView test16(@RequestParam("name")String name){
ModelAndView mv = new ModelAndView();
mv.setViewName("hello");
mv.addObject("msg", "接收普通的请求参数:" + name);
return mv;
}
得到结果
url:localhost:8080/hello/show16?name=cc
页面:
接收普通的请求参数:cc
package com.example.accessingdatamysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AccessingDataMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataMysqlApplication.class, args);
}
}
check.html
Check User List
Check User List
Name
Email
操作
编辑
删除
添加新信息
edit.html
Edit User
编辑信息
返回列表
form.html
Form
表格
list.html
List
信息系统
Name
Email
操作
编辑
删除
添加新信息
删除全部用户信息
这里的页面可以通过设置css样式表等方式进行改进
结果:可以通过前端创建用户,并加入到mysql数据库中