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、换个没有被占用的端口号运行  
上一篇:2019.7.14 义乌模拟赛 T4 city


下一篇:基于Hadoop的项目实战-职位数据 从数据采集(Selenium)、数据预处理、Hive分析、Sqoop导入MySQL 进一步用Javaweb可视化,最后进行机器学习、数据挖掘分析