在Spring Boot中将表单数据插入到MySQL数据库中,你可以按照以下步骤进行操作:
application.properties
文件中添加以下配置:spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
替换db_name
为你的数据库名称,username
和password
为你的MySQL用户名和密码。
User
的实体类,代码示例如下:import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 省略构造器、getter和setter方法
}
UserRepository
的接口,代码示例如下:import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository {
}
UserController
的控制器,代码示例如下:import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/form")
public String showForm(Model model) {
model.addAttribute("user", new User());
return "userForm";
}
@PostMapping("/save")
public String saveUser(User user) {
userRepository.save(user);
return "redirect:/users/form";
}
}
User Form
User Form
http://localhost:8080/users/form
来打开表单页面。填写表单数据并提交后,表单数据将会保存到MySQL数据库中。请确保你已经添加了相关的依赖,如spring-boot-starter-data-jpa
和mysql-connector-java
。
这就是将表单数据插入到MySQL数据库中的基本步骤。根据你的具体需求,你可能需要进行更多的配置和操作。
下一篇:表单数据没有附加文件对象。