Springboot第五篇:結合myBatis進行SQL操作


 前提:和之前同樣的,本篇會從前端和后台一起講述關於SQL的select操作(其他操作原理大致類似,不多做解釋了)。

 

大致流程:前端通過AJAX將數據發送到后台的路由,后台路由會根據發送的數據進行SQL操作,並返回對應數據。

 


 

1:DB的table表建立

 

我們這邊只建立一個簡單的table表,建表的語句大致如下(本地為mysql):

CREATE TABLE `user_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
)

 

建立好table以后,我們插入一條記錄,執行語句:INSERT INTO `user_info`(`id`,`name`)VALUES(1,‘zhuyt');

 


 

2:前端fetch

 

fetch與劇中的url需要根據自己的后台設置,對應后台執行的是select操作,代碼如下:

fetch("http://localhost:8080/index/userInfo",{
    method:'post', // or 'PUT'
    headers:{
        "Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"
    },
    body:"id=1", // data can be `string` or {object}!
}).then(res => res.json()).then(data => {
    console.log(data);
}).catch(error => console.error('Error:', error));    

 


 

3:后台

 

首先關於pom,我們要加入兩個依賴模塊,第一個模塊是關於mybatis與mysql的,第二個模塊是關於JSON格式相關的內容:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.15</version>
</dependency>
<dependency> 
    <groupId>net.sf.json-lib</groupId> 
    <artifactId>json-lib</artifactId> 
    <version>2.4</version> 
    <classifier>jdk15</classifier> 
</dependency> 

 

關於controller模塊,代碼如下:

package maven.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import maven.example.service.UserService;
import net.sf.json.JSONArray;

@RestController
@RequestMapping(value = "/index")
public class IndexController {
    
    @Autowired
    private UserService userService;
    
    @RequestMapping("/userInfo")
    public JSONArray userInfo(@RequestParam("id") String id) {
        return userService.getUserInfo(Integer.valueOf(id));
    }
}

 

關於service模塊,代碼如下:

package maven.example.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import maven.example.entity.UserEntity;
import maven.example.mapper.UserMapper;
import net.sf.json.JSONArray;

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    public JSONArray getUserInfo(Integer id){
        List<UserEntity>li = userMapper.getUserInfo(id);
        JSONArray listArray = JSONArray.fromObject(li);
        return listArray;
    }
}

 

關於UserMapper接口模塊,代碼如下:

package maven.example.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import maven.example.entity.UserEntity;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM USER_INFO WHERE ID=#{id}")
    @Results({
        @Result(property = "id", column = "id"),
        @Result(property = "name", column = "name")
    })
    List<UserEntity>getUserInfo(@Param("id") Integer id);
}

 

關於model模塊,代碼如下:

package maven.example.entity;

public class UserEntity {
    private Integer id;
    private String name;
    
    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;
    }
}

 

完整的后台代碼可以去以下地址拉取,https://github.com/nnnnnjjjjj/springboot.git

 


 

4:執行

 

我們打開瀏覽器,輸入對應的地址,並點擊F12鍵,可以看到確實打印出了DB查詢到的數據。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM