Mybatis进行增删改查操作

在上一篇博客中大致讲述了如何使用mybatis的相关插件自动的生成mapper.xml和mapper接口,如果不清楚的可以参考一下上篇博客《mybatis自动生成接口插件的简单使用》
在上篇博客的基础上,填在相应的代码,主要包括:相关的service和controller,以及application.yaml文件等,下面来进行一次讲解!
首先看一下applicaiton.yaml文件,因为使用的是springboot框架,需要通过application.yaml文件进行相应的数据源配置,文件内容如下:

#指明数据源名称
spring.datasource.name: mysql
#指明数据库连接的url,后面紧跟的参数指明编码类型和是否使用ssl
spring.datasource.url: jdbc:mysql://127.0.0.1:3306/world?characterEncoding=utf8&useSSL=true
#spring.datasource.url: jdbc:mysql://127.0.0.1:3306/world
#连接数据库使用的用户名
spring.datasource.username: root
#连接数据库使用的登录密码
spring.datasource.password: root123
#在框架中使用的dataSource的类型
spring.datasource.type: com.alibaba.druid.pool.DruidDataSource
#数据库连接器的驱动类
spring.datasource.driver-class-name: com.mysql.jdbc.Driver
#指明mapper.xml文件的类型
mybatis.mapperLocations: classpath:mybatis/mapping/*.xml
#指定在mapper.xml文件中使用到类型别名所在的包的包名
mybatis.typeAliasesPackage: com.entities

在这里我们只以City这表为例介绍一下,如何使用mybatis进行简单的操作!
表City对应的mapper.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--指明当前xml文件对应在java文件中对的接口-->
<mapper namespace="com.interfaces.CityMapper">
    <!--查询语句,通过id查询一条关于城市的记录,查询的结果直接使用City类来进行封装-->
    <select id="selectCityById" parameterType="int" resultType="com.entities.City">
    SELECT * FROM city WHERE ID=#{id,jdbcType=INTEGER}
    </select>
    <!--向City表中插入一条新纪录-->
    <insert id="insertCity" parameterType="com.entities.City">
        insert into city
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                ID,
            </if>
            <if test="name != null">
                Name,
            </if>
            <if test="countrycode != null">
                CountryCode,
            </if>
            <if test="district != null">
                District,
            </if>
            <if test="population != null">
                Population,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null">
                #{name,jdbcType=CHAR},
            </if>
            <if test="countrycode != null">
                #{countrycode,jdbcType=CHAR},
            </if>
            <if test="district != null">
                #{district,jdbcType=CHAR},
            </if>
            <if test="population != null">
                #{population,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <!--根据指定的Id,从city表中删除一条记录-->
    <delete id="deleteCityById" parameterType="java.lang.Integer">
        delete from city
        where ID = #{id,jdbcType=INTEGER}
    </delete>
    <!--根据指定的Id,更新city表中的一条记录-->
    <update id="updateCityById" parameterType="com.entities.City">
        UPDATE city set Name=#{name,jdbcType=CHAR},
        CountryCode=#{countrycode,jdbcType=CHAR},
        District=#{district,jdbcType=CHAR},
        Population=#{population,jdbcType=INTEGER}
        WHERE ID=#{id,jdbcType=INTEGER}
    </update>
</mapper>

关于mapper.xml中的语句也还简单,虽然可能不会写,但是绝对是可以看的懂的(前提是你熟悉数据库的sql语句)!

编写service文件:

package com.services;

import com.entities.City;
import com.interfaces.CityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CityService {

    @Autowired
    CityMapper cityMapper;

    public City selectCityById(int id){
        return cityMapper.selectCityById(id);
    }

    public int updateCityById(City city){
        return cityMapper.updateCityById(city);
    }

    public int deleteCityById(int id){
        return cityMapper.deleteCityById(id);
    }

    public int insertCity(City city){
        return cityMapper.insertCity(city);
    }
}

编写CityController文件:

package com.controllers;

import com.dto.ResponseDto;
import com.entities.City;
import com.services.CityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "CityController")
public class CityController {
    //自动注入CityService
    @Autowired
    private CityService cityService;

    @RequestMapping(value = "/city/{id}",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "selectCityById")
    public ResponseDto selectCityById(@PathVariable(value = "id") @ApiParam(value = "记录的Id") int id){
        City result =  cityService.selectCityById(id);
        ResponseDto dto = new ResponseDto();
        dto.setData(result);
        dto.setStatus("200");
        dto.setTimestamp(String.valueOf(System.currentTimeMillis()));
        return dto;
    }

    @RequestMapping(value = "/insert_city",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseDto insertCity(@RequestBody City city){

        int result =  cityService.insertCity(city);
        ResponseDto dto = new ResponseDto();
        dto.setData(result);
        dto.setStatus("200");
        dto.setTimestamp(String.valueOf(System.currentTimeMillis()));
        return dto;
    }

    @RequestMapping(value = "/delete_city/{id}",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseDto deleteCityById(@PathVariable(value = "id") int id){
        int result =  cityService.deleteCityById(id);
        ResponseDto dto = new ResponseDto();
        dto.setData(result);
        dto.setStatus("200");
        dto.setTimestamp(String.valueOf(System.currentTimeMillis()));
        return dto;
    }

    @RequestMapping(value = "/update_city",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseDto updateCityById(@RequestBody City city){
        int result =  cityService.updateCityById(city);
        ResponseDto dto = new ResponseDto();
        dto.setData(result);
        dto.setStatus("200");
        dto.setTimestamp(String.valueOf(System.currentTimeMillis()));
        return dto;
    }
}

在本次测试的工程中,使用了swagger自动生成接口文档框架,使用这种框架,不仅在开发时不需要我手动编写文档,还方便我们开发人员对自己编写的文档进行自测,在这里只是使用一下,不做详细介绍!

swagger框架的相关配置:

package com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(getApiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(getApiInfo())
                .enable(true);
    }

    private ApiInfo getApiInfo(){
        return new ApiInfoBuilder()
                .title("xxxx后端接口文档")
                .description("后端接口文档")
                .version("1.0.0")
                .build();
    }
}

在工程入口处添加相关的swagger功能注解,代码如下:

package com;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Properties;
import java.util.Scanner;

@SpringBootApplication
@RestController
//指定程序到com.interfaces包下查询mapper接口
@MapperScan(basePackages = "com.interfaces")
@EnableTransactionManagement
//开启swagger功能
@EnableSwagger2
public class ProviderWorldApplication {

    @RequestMapping(value = "/")
    public String getHelloWorld(){
        return "HelloWorld";
    }


    public static void main(String[] args){
//        Scanner scanner = new Scanner(System.in);
//        String port = null;
//        if(scanner.hasNext()){
//            port = scanner.nextLine();
//        }else{
//            port = "8080";
//        }
        SpringApplication  app = new SpringApplication(ProviderWorldApplication.class);
        Properties properties = new Properties();
        //在9000端口上启动web服务
        properties.setProperty("server.port","9000");
        app.setDefaultProperties(properties);
//        app.setAddCommandLineProperties(true);
        app.run(args);
    }
}

在程序运行起来之后,可以通过输入http://localhost:9000/swagger-ui.html#!/来进入接口的描述页面,大致内容如下:
这里写图片描述

通过填写参数,使用swagger提供的测试按钮直接测试相应的接口功能,可以很好的测试项目中的接口,在这里就给出测试结果,相应的测试都是可以正常运行的。

关于本次demo没有数据库数据的可以到world.sql下载。然后通过数据库可视化工具或者命令行直接运行sql文件即可。

猜你喜欢

转载自blog.csdn.net/u011043551/article/details/80208369