龙空技术网

Springboot使用Mybatis添加数据的示例

洞悉科学 48

前言:

而今咱们对“js给json添加数据”大体比较关切,咱们都想要了解一些“js给json添加数据”的相关资讯。那么小编也在网络上搜集了一些对于“js给json添加数据””的相关内容,希望大家能喜欢,小伙伴们快快来学习一下吧!

在Spring Boot框架下结合MyBatis技术将页面数据保存到数据库中,你需要遵循几个基本步骤。下面是一个简单的例子来说明如何做到这一点:

1. 添加依赖

首先,确保你的pom.xml(如果你使用Maven)中包含了Spring Boot、MyBatis以及数据库驱动(例如MySQL)的依赖。

2. 配置数据源和MyBatis

application.propertiesapplication.yml中配置数据源信息,如URL、用户名和密码。同时,配置MyBatis的mapper文件位置等信息。

3. 创建实体类

根据你的数据库表结构,创建相应的Java实体类。这些类将映射到数据库中的表。

4. 创建Mapper接口

创建MyBatis的Mapper接口,定义与数据库操作相关的方法。MyBatis会自动为你生成这些方法的实现。

5.创建Service类

创建服务层(Service Layer)来处理业务逻辑。

6. 创建Mapper XML文件

创建与Mapper接口对应的XML文件,定义SQL语句。这些SQL语句将用于执行数据库操作。

7. 创建控制器(Controller)

创建Spring MVC的控制器类,用于处理前端请求。在这个类中,你将接收前端发送的数据,并将其保存到数据库中。

8. 处理前端请求并保存数据

在控制器中,编写一个方法来处理前端发送的POST请求。从请求中获取数据,将其封装成实体类对象,然后调用Mapper接口中的方法将数据保存到数据库中。

实体类

public class Editor {   private Integer id;   private String title;   private String content;   // getters and setters}

Mapper接口

public interface EditorMapper {   int insertEditor(Editor editor);}

Service类

@Servicepublic class EditorService {   @Autowired   private EditorMapper editorMapper;   public int insertEditor(Editor editor){       return editorMapper.insertEditor(editor);  }}

Mapper XML文件

<mapper namespace="com.example.demo.demos.mapper.EditorMapper">   <insert id="insertEditor" parameterType="Editor">      INSERT INTO editor(title,content) VALUES (#{title}, #{content})   </insert></mapper>

控制器

@RestController@RequestMapping("/editor")public class EditorController {   @Autowired   private EditorService editorService;   @PostMapping("/save")   public ResponseEntity<String> createUser(@RequestBody Editor editor) {       int result=editorService.insertEditor(editor);       if (result > 0) {           return ResponseEntity.ok("User created successfully");      } else {           return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to create user");      }  }}
前端HTML(classpath:/static)
<!DOCTYPE html><html lang="en"><head>   <meta charset="UTF-8">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <title>添加数据页面</title></head><body><h1>添加数据页面</h1><form id="dataForm">   <div>       <label >标题:</label>       <input type="text" id="titleInput" name="title" required>   </div>   <div>       <label >内容:</label>       <input type="text" id="content" name="content" required>   </div>   <button type="button" onclick="createEditor()">添加数据</button></form><script>//以下为添加数据的JS代码   function createEditor() {       // 获取表单输入值       const title = document.getElementById('titleInput').value;       const content = document.getElementById('content').value;       // 创建用户对象       const editorData = {           title: title,           content: content      };       fetch('/editor/save', {           method: 'POST', // 或者是 'post'           headers: {               'Content-Type': 'application/json', // 告诉服务器你发送的是JSON格式的数据          },           body: JSON.stringify(editorData) // 将JavaScript对象转换为JSON字符串      })          .then(response => {           if (response.ok) {           return response.text(); // 或者 response.json() 如果后端返回的是JSON      } else {           throw new Error('Network response was not ok.');      }  })  .then(data => {           console.log(data); // 打印后端返回的消息       alert('Successfully');       window.location.href = '/list'; // 跳转到列表页面       // 根据返回的数据进行UI更新等操作  })  .catch(error => {           console.error('There has been a problem with your fetch operation:', error);       // 错误处理,例如显示错误信息给用户       alert('Failed to create user');  });}</script></body></html>

标签: #js给json添加数据