1. 程式人生 > 其它 >SpringBoot整合mybatis實現增刪改查

SpringBoot整合mybatis實現增刪改查

1、整合好環境後:環境搭建 見SpringBoot開發環境搭建 整合mybatis+熱部署+靜態檔案載入 2、在test包下建立: #entity目錄 建立物件pojo例項類 用於IOC封裝物件
package com.example.springBoot.modules.test.entity;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

public class City {
    private Integer cityId;
    private String cityName;
    private String localCityName;
    private Integer countryId;
    private String district;
    
private Integer population; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date dateModified; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date dateCreated; // 自行新增 get、set 方法 public Integer getCityId() { return cityId; }
public void setCityId(Integer cityId) { this.cityId = cityId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getLocalCityName() { return localCityName; }
public void setLocalCityName(String localCityName) { this.localCityName = localCityName; } public Integer getCountryId() { return countryId; } public void setCountryId(Integer countryId) { this.countryId = countryId; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public Integer getPopulation() { return population; } public void setPopulation(Integer population) { this.population = population; } public Date getDateModified() { return dateModified; } public void setDateModified(Date dateModified) { this.dateModified = dateModified; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } }
在common.entity目錄下建立SearchBean,提供多業務呼叫實現分頁搜尋查詢
package com.example.springBoot.modules.common.entity;

public class SearchBean {
    private final static int DEFAULT_CURRENT_PAGE=1;
    private final static int DEFAULT_PAGE_SIZE=5;
    private int currentPage;
    private int pageSize;
    private String orderBy;
    private String direction;
    private String keyword;

    public void initSearchBean(){
        if (this==null){
            return;
        }
        this.currentPage=DEFAULT_CURRENT_PAGE;
        this.pageSize=DEFAULT_PAGE_SIZE;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public String getOrderBy() {
        return orderBy;
    }

    public void setOrderBy(String orderBy) {
        this.orderBy = orderBy;
    }

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }
}
dao目錄:注入slq語句到介面方法 建立cityDao
package com.example.springBoot.modules.test.dao;
import com.example.springBoot.modules.common.entity.SearchBean;
import com.example.springBoot.modules.test.entity.City;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;

@Mapper
@Repository
public interface CityDao {
    /**
     * 插入資料
     */
    @Insert("insert into test_city(city_name,local_city_name,country_id,date_created) " +
            "values(#{cityName},#{localCityName},#{countryId},#{dateCreated})")
    @Options(useGeneratedKeys = true, keyColumn = "city_id", keyProperty = "cityId")
    void insertCity(City city);

    /**
     * 根據id更新數
     */
    @Update("update test_city set city_name=#{cityName},country_id=#{countryId}," +
            "local_city_name=#{localCityName} " +
            "where city_id=#{cityId} ")
    void updateCity(City city);

    @Delete("delete from test_city where city_id=#{cityId}")
    void deleteCity(City city);

    @Select("select * from test_city where city_id=#{cityId} ")
    City getCityByCityId(int cityId);

    @Select("select * from test_city where country_id = #{countryId}")
    List<City> getCitiesByCountryId(int countryId);

    @Select("<script>"
            + "select * from test_city "
            + "<where> "
            + "<if test='keyword != \"\" and keyword != null'>"
            + " and (city_name like '%${keyword}%' or "
            + " local_city_name like '%${keyword}%') "
            + "</if>"
            + "</where>"
            + "<choose>"
            + "<when test='orderBy != \"\" and orderBy != null'>"
            + " order by ${orderBy} ${direction}"
            + "</when>"
            + "<otherwise>"
            + " order by city_id desc"
            + "</otherwise>"
            + "</choose>"
            + "</script>")
    List<City> getCitesBySearchBean(SearchBean searchBean);
}
service目錄 建立cityService介面檔案
package com.example.springBoot.modules.test.service;

import com.example.springBoot.modules.common.entity.Result;
import com.example.springBoot.modules.common.entity.SearchBean;
import com.example.springBoot.modules.test.entity.City;
import com.github.pagehelper.PageInfo;

import java.util.List;

public interface CityService {
    Result<City> insertCity(City city);
    Result<City> updateCity(City city);
    Result<City>  deleteCity(City city);
    City getCityByCityId(int cityId);
    List<City> getCitiesByCountryId(int countryId);
    PageInfo<City> getCitesBySearchBean(SearchBean searchBean);
}
建立cityServiceImpl業務實現檔案
package com.example.springBoot.modules.test.service.Impl;

import com.example.springBoot.modules.common.entity.Result;
import com.example.springBoot.modules.common.entity.SearchBean;
import com.example.springBoot.modules.test.dao.CityDao;
import com.example.springBoot.modules.test.entity.City;
import com.example.springBoot.modules.test.service.CityService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityDao cityDao;
    @Override
    public Result<City> insertCity(City city) {
        city.setDateCreated(new Date());
        cityDao.insertCity(city);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "insertCity success",city);
    }

    @Override
    public Result<City> updateCity(City city) {
        cityDao.updateCity(city);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "updateCity success",city);
    }

    @Override
    public Result<City> deleteCity(City city) {
        cityDao.deleteCity(city);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "deleteCity success",city);
    }

    @Override
    public City getCityByCityId(int cityId) {
        return cityDao.getCityByCityId(cityId);
    }


    @Override
    public List<City> getCitiesByCountryId(int countryId) {
        return Optional
                .ofNullable(cityDao.getCitiesByCountryId(countryId))
                .orElse(Collections.emptyList());
    }

    @Override
    public PageInfo<City> getCitesBySearchBean(SearchBean searchBean) {
        //先給pageSize currentPage 附上初始值
        searchBean.initSearchBean();

        PageHelper.startPage(searchBean.getCurrentPage(),searchBean.getPageSize());

        return new PageInfo<>(Optional
        .ofNullable(cityDao.getCitesBySearchBean(searchBean))
        .orElse(Collections.emptyList()));
    }
}
ccontroller目錄:建立cityController,實現對頁面的資料輸出 當application.properties中配置了http和https兩種協議時 可以通過兩個地址訪問同一controller類方法 htttp://127.0.0.1:80/city/insertCity 同理:80http預設埠號 不安全 443https預設埠號 安全 https://127.0.0.1:443/city/insertCity
package com.example.springBoot.modules.test.controller;

import com.example.springBoot.modules.common.entity.Result;
import com.example.springBoot.modules.common.entity.SearchBean;
import com.example.springBoot.modules.test.entity.City;
import com.example.springBoot.modules.test.service.CityService;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
public class CityController {
    @Autowired
    private CityService cityService;

    /**
     * url: http://127.0.0.1/api/city  ----POST
     * {"cityName":"dream","localCityName":"夢幻之城","countryId":"522"}
     *
     */
    @PostMapping(value = "/insertCity", consumes = "application/json")
    public Result<City> insertCity(@RequestBody City city) {
        return cityService.insertCity(city);
    }

    /**
     * json格式{"cityId":"2260","cityName":"devil","localCityName":"魔鬼之都","countryId":"000"}
     * form表單格式:cityId=2260 cityName=devil localCityName=魔鬼之都  countryId=000
     * url:https://127.0.0.1/api/updateCity   ----PUT
     */
    @PutMapping(value = "/updateCity", consumes = "application/x-www-form-urlencoded")
    public Result<City> updateCity(@ModelAttribute City city) {
        return cityService.updateCity(city);
    }

    /**
     * {"cityId":2259}
     * url:https://127.0.0.1/api/deleteCity  --DELETE
     */
    @DeleteMapping(value = "/deleteCity", consumes = "application/json")
    public Result<City> deleteCity(@RequestBody City city) {
        return cityService.deleteCity(city);
    }

    /**
     * 127.0.0.1:8080/api/getCityByCityId/1890---- GET
     */
    @GetMapping(value = "/getCityByCityId/{cityId}")
    public City getCityByCityId(@PathVariable int cityId) {
        return cityService.getCityByCityId(cityId);
    }

    /**
     *
     * 127.0.0.1:8080/api/cities/522 ---- GET
     */
    @GetMapping("/cities/{countryId}")
    public List<City> getCitiesByCountryId(@PathVariable int countryId) {
        return cityService.getCitiesByCountryId(countryId);
    }
    /**
     * 127.0.0.1:8080/api/cities---- post
     * {"currentPage":1,"pageSize":5,"orderBy":"city_name","direction":"desc","keyword":""}
     */
    @PostMapping(value = "/cities", consumes = "application/json")
    public PageInfo<City> getCitesBySearchBean(@RequestBody SearchBean searchBean){
        return cityService.getCitesBySearchBean(searchBean);
    }
}
使用Postman測試軟體 進行測試,獲取資料是否正常 常見問題: 訪問路徑問題:http/https協議 + ip地址 + 埠號 + Mapper地址(多級地址)+請求資料 最常見端口占用問題: 1、解決方法: 開啟windows執行框 輸入netstat -aon|findstr "被佔用的埠號" 回車 檢視被佔用的埠的程序 開啟工作管理員 停止佔用的程序 2、換個沒有被佔用的埠號執行