Springboot入門:實現簡單的增刪改查(前後端分離)前端使用vue框架

Spring Boot簡介
Spring是java企業版的輕量級代替品,爲企業java開發提供了一種相對簡單的方法,通過依賴注入和麪向切面編程,用簡單的java對象實現EJB的功能

Spring的組件代碼是輕量級的,但他的配置卻是重量級的。

第一階段:
在spring1.X時代,使用Spring開發全部都是xml配置的bean,隨着項目的擴大,我們需要把xml配置到不同的配置文件裏邊,需要頻繁的在開發類和配置文件之間進行切換

第二階段:註解配置

在Spring2.X時代,隨着JDK1.5帶來的註解支持,Spring提供聲明的註解(例如@Component @sevice),大大減少了配置量。主要使用的方式是應用的基本配置(如數據庫配置)用xml,業務配置用註解

第三階段:java配置

Spring3.0引入了基於Java的配置能力,是一種安全的可以重構的配置文件,可以代替xml,我們目前處於的時代,Spring4.x和spring Boot都推薦適用java配置

Spring Boot的目標
爲所有的開發提供一個從根本上更快的入門
開箱即用,通過自己設置參數,快速擺脫這種方式
提供了一些大型項目中非常常見的非公能性特性,如內嵌服務器、安全、指標、健康檢測、外部化配置等
絕對沒有代碼生成,無需配置xml配置

Spring boot入門
1、下載工具STS
地址:https://spring.io/tools3/sts/legacy
通過.eclipseproduct(在eclipse下載目錄中)查看java版本下載與之對應的STS工具
查看java版本:
在這裏插入圖片描述

在官網找到對應的版本的STS進行下載
在這裏插入圖片描述

解壓壓縮包並執行可運行的exe
點擊運行
2、新建springboot項目
創建方式 file -new-new spring Start
在這裏插入圖片描述
點擊next-finish
一個簡單的springboot環境基本搭建完畢
springboot實現增刪查改

新建項目的基本結構:
1、在resource中的mapper編寫sql語句
2、Java中的mapper所寫接口的接口名,與resource中的mapper中的id相對應
3、編寫實體類,實體類中的字段名要與數據庫中的字段相匹配(注意數據類型)
4、Service層,服務層的接口
5、Seviceimpl,接口的實現類
6、Filter:過濾層,用於過濾路徑
7、Controller:控制層,用於處理業務邏輯
8、Pom.xml:添加maven依賴
9、Application.prperties:配置文件的編寫
第一步:創建數據庫中一張user表
Sql文件(直接運行即可):
/*
Navicat MySQL Data Transfer

Source Server : 10.2.10.201111
Source Server Version : 50540
Source Host : 10.2.10.201:3306
Source Database : test

Target Server Type : MYSQL
Target Server Version : 50540
File Encoding : 65001

Date: 2019-12-05 15:37:05
*/

SET FOREIGN_KEY_CHECKS=0;


– Table structure for user


DROP TABLE IF EXISTS user;
CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) DEFAULT NULL,
password varchar(100) DEFAULT NULL,
number varchar(100) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=32142342 DEFAULT CHARSET=latin1;


– Records of user


INSERT INTO user VALUES (‘1’, ‘zhangsan122’, ‘123’, ‘996’);
INSERT INTO user VALUES (‘2’, ‘wangwu’, ‘456’, ‘955’);
INSERT INTO user VALUES (‘3’, ‘lisi’, ‘789’, ‘007’);
INSERT INTO user VALUES (‘4’, ‘’, ‘weu1387’, ‘2938’);

第二步:根據數據表創建實體類

package com.example.demo.entity;
/***
 * 用戶實體類
 * @author zyh *
 */
public class User {
	
	
	private Integer page;
	private Integer size;
	private int id;
	private String name;
	private String password;
	private String number;
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;  
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}



	public Integer getPage() {
		return page;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public Integer getSize() {
		return size;
	}

	public void setSize(Integer size) {
		this.size = size;
	}

	@Override
	public String toString() {
		return "User [page=" + page + ", size=" + size + ", id=" + id + ", name=" + name + ", password=" + password
				+ ", number=" + number + "]";
	}
}

第三步:編寫mapper接口Usermapper
注意:記得添加註解@Mapper

package com.example.demo.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.example.demo.entity.User;
@Mapper
public interface UserMapper {
	/**
	 * 通過名字查詢
	 * @param name
	 * @return
	 */
	List<User> findUserByName(String name);
	/**
	 * 查詢所有用戶
	 * @return
	 */
	
	public List<User> ListUser();
	
	/**
	 * 插入一個用戶
	 * @param user
	 * @return
	 */
	public int insertUser(User user);
	/**
	 * 根據id刪除一條數據
	 * @param id
	 * @return
	 */
	
	public int delete(int id);
	/**
	 * 更新用戶
	 * @param user
	 * @return
	 */
	public int Update(User user);
	/**
	 * 分頁查詢語句,根據sql進行分頁
	 * @param page
	 * @param size
	 * @return
	 */
	public List<User> getAllUserByPage(Integer page,Integer size);
	/**
	 * 獲取用戶總數通過數據庫獲取
	 * @return
	 */
	public Long getTotal();
	
}

第四步:編寫resource中mapper的sql語句
注意:id字段與上一步中接口名必須一致,返回類型需要與你的實體類相匹配

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE mapper PUBLIC
        "-//mybatis.org//DTD com.example.Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
	<resultMap id="result" type="com.example.demo.entity.User">
		<result property="name" column="name" />
		<result property="password" column="password" />
		<result property="number" column="number"/>

	</resultMap>
<!-- 查詢所有的角色 -->
	<select id="ListUser" resultMap="result">
		SELECT * FROM user
	</select>
<!-- 通過名字查詢所有數據 -->
	<select id="findUserByName" resultMap="result">
		SELECT * FROM user where name=#{name}
	</select>
	<!-- 數據庫的分頁查詢語句。。。有問題-->
	<select id="getAllUserByPage" resultMap="result">
     select
     *
     FROM
     user
     limit #{page}, #{size}
    </select>
    
    <select id="getTotal" resultType="java.lang.Long">
    select count(*) from user
    </select> 



	<!--分特查詢的語句    <select id="getAllUserByPage" resultMap="com.example.demo.entity.User.RespPageEntity">
	select * FROM user limit #{page}, #{size}
     </select>
	<select id="getTotal" resultType="com.example.demo.entity.User.RespPageEntity">
		select count(*) from user;
	</select>
	-->
<!-- 插入一條數據 -->
	<insert id="insertUser" parameterType="com.example.demo.entity.User"
		keyProperty="id" useGeneratedKeys="true">
		INSERT INTO user
		(
		id,name,password,number
		)
		VALUES (
		#{id},
		#{name, jdbcType=VARCHAR},
		#{password, jdbcType=VARCHAR},
		#{number}
		)
	</insert>
	<!-- 通過id刪除一條數據 -->
	<delete id="delete" parameterType="int">
		delete from user where id=#{id}
	</delete>
	<!-- 增加一個用戶 -->
	<update id="Update" parameterType="com.example.demo.entity.User">
	update user set user.name=#{name},user.password=#{password},user.number=#{number} where user.id=#{id}
	</update>
</mapper>

第五步:編寫service層(可進行分類接口與實現)

package com.example.demo.service;

import java.util.List;

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

import com.example.demo.entity.RespPageEntity;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;





@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
    /**
     * 通過名字查詢
     * @param name
     * @return
     */
	public List<User> findByName(String name) {
		return userMapper.findUserByName(name);
	}
	
    /**
     * 插入一個用戶
     * @param user
     * @return
     */
	public User insertUser(User user) {
		userMapper.insertUser(user);
		return user;
	}
	/**
	 * 查詢所有角色
	 * @return
	 */
	public List<User> ListUser(){
		return	userMapper.ListUser();
	}
	
	/**
	 * 更新用戶
	 * @param user
	 * @return
	 */
	public int Update(User user){
		return userMapper.Update(user);
	}
	/**
	 * 根據id刪除用戶
	 * @param id
	 * @return
	 */
	public int delete(int id){
		return userMapper.delete(id);
	}
	
	/**
	 * 分頁查詢
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public PageInfo<User> getAllUser(int pageNo,int pageSize){
		PageHelper.startPage(pageNo, pageSize);
		List<User> list =userMapper.ListUser();
		//返回一個pageinfo
		PageInfo<User> page=new PageInfo<User>(list);
		return page;
		
	}
	/**
	 * 數據庫分頁查詢
	 * @param page
	 * @param size
	 * @return
	 */
	@Transactional
	public RespPageEntity getALLUserByPage(Integer page,Integer size){
		RespPageEntity pageEntity =new RespPageEntity();
		//默認從0開始
		if(page !=null && size!=null){
			page = (page-1)*size;
		}
		//獲取當前用戶信息
		List<User> users =userMapper.getAllUserByPage(page, size);
		pageEntity.setDate(users);
		//獲取當前用戶總量
		Long total=userMapper.getTotal();
		pageEntity.setTotal(total);
		return pageEntity;
		
	}
}

第六步:編寫controller中的CRUD(增刪查改)
注意:需要一些特定的註解
如:@CrossOrigin 進行跨域訪問
@RestController 表示爲控制層
@RequestMapping(value = “/CRUD”, method = { RequestMethod.GET, RequestMethod.POST })
向前端的供應的接口(get/post都進行了採用)
@ResponseBody@RequestBody 將User轉化爲JSON對象
@Autowired 自動注入

package com.example.demo.controller;

import java.util.List;
import javax.naming.spi.DirStateFactory.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;

@CrossOrigin
@Configuration
@RestController
@RequestMapping(value = "/CRUD", method = { RequestMethod.GET, RequestMethod.POST })
public class CRUD {
	@RequestMapping("/ListUser")
	@ResponseBody
	@CrossOrigin("http://localhost:8080")
	/**
	 * 查詢所有用戶
	 * 
	 * @return
	 */
	public List<User> ListUser() {
		return userservice.ListUser();
	}

	@RequestMapping("/ListUserByname")
	@ResponseBody
	@CrossOrigin("http://localhost:8080")
	/**
	 * 根據名字查詢
	 * 
	 * @param name
	 * @return
	 * 
	 */
	public List<User> ListUserByname(String name) {
		return userservice.findByName(name);
	}

	@Autowired
	private UserService userservice;

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@CrossOrigin("http://localhost:8080")
	/**
	 * 根據id刪除
	 * 
	 * @param id
	 * @return
	 */
	public String delete(@RequestBody int id) {
		int result = userservice.delete(id);
		if (result >= 1) {
			return "刪除成功";
		} else {
			return "刪除失敗";
		}
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@CrossOrigin("http://localhost:8080")
	/**
	 * 更新一個用戶
	 * 
	 * @param user
	 * @return
	 */
	public String update(@RequestBody User user) {
		int result = userservice.Update(user);
		if (result >= 1) {
			return "修改成功";
		} else {
			return "修改失敗";
		}

	}

	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	@CrossOrigin("http://localhost:8080")
	/**
	 * 插入一個用戶
	 * 
	 * @param user
	 * @return
	 */
	public User insert(@RequestBody User user) {
		return userservice.insertUser(user);
	}

	@RequestMapping("into")
	public Result into(@RequestBody User user) {
		User user1 = new User();
		user1.setId(user.getId());
		user1.setName(user.getName());
		user1.setPassword(user.getPassword());
		user1.setNumber(user.getNumber());
		/// return new Result(ResultCode., user);
		// Result rs=new Result(arg0, arg1)
		return null;
	}

	/**
	 * 插入一條新數據
	 * 
	 * @param users
	 */
	@RequestMapping(value = "/insertUser", method = { RequestMethod.POST })
	@ResponseBody
	@CrossOrigin("http://localhost:8080")

	public String insertUser(@RequestBody User users) {
		User rtn = null;
		if (users != null) {
			rtn = userservice.insertUser(users);
		} else {
			System.out.println("沒有數據傳入");
		}

		if (rtn != null) {
			System.out.println("插入成功");
			System.out.println(rtn.toString());
			return "sucessful";
		} else {
			System.out.println("插入失敗");
		}
		return "fail";

	}

	@PostMapping("save")
	public String save(@RequestBody User user) {
		return null;
	}
}

第七步:根據特定的需求編寫的過濾器(原理暫時未懂)

Myconfiguration

package com.example.demo.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SuppressWarnings("deprecation")
@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

webmvcConfig

package com.example.demo.filter;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @Author: zyh
 * @Date: now
 * @Description:
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

第八步:編寫配置文件連接數據庫

package com.example.demo.filter;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @Author: zyh
 * @Date: now
 * @Description:
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

第九步:編寫pom文件,添加maven依賴

package com.example.demo.filter;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @Author: zyh
 * @Date: now
 * @Description:
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

第十步:啓動項目SpringbootMybatisApplication

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootMybatisApplication.class, args);
	}
}

至此,簡單的springboot增刪改查的後端基本功能已經實現
順序可以不一致

總結
1、前端數據刪除存在問題,定義的int類型的id根據id來刪除數據,刪除後後臺響應了刪除的行列值,但數據庫中該數據並未被刪除
2、分頁查詢不能使用分頁插件來進行分頁(無效接口),因爲前端使用的vue框架,後端應使用數據庫的分頁查詢,但是使用該分頁接口後會報錯
nested exception is org.apache.ibatis.binding.BindingException: Parameter ‘page’ not found. Available parameters are [arg1, arg0, param1, param2]
推測是由於mybatis中的

<select id="getAllUserByPage" resultMap="result">
 select
 *
 FROM
 user
 limit #{page}, #{size}
</select>

<select id="getTotal" resultType="java.lang.Long">
select count(*) from user
</select> 

其中resultMap="result"出現類型不匹配的問題
該問題未解決

使用postman測試
在這裏插入圖片描述感謝原作者:原博客地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章