SpringBoot整合MyBatis

1、前言

现在开发一个项目没使用持久化框架的应该是极少了,之前使用Spring整合MyBatis,需要配置一堆的配置文件。现在使用SpringBoot来整合MyBatis就很简单了,SpringBoot集成了SpringJDBC与JPA,但是没有集成MyBatis,所以想要使用MyBatis就要自己去集成。主要是在Spring Boot中集成MyBatis,可以选用基于注解的方式,也可以选择xml文件配置的方式。官方推荐使用xml文件配置。个人也比较喜欢使用xml文件配置。

2、引入MyBatis依赖

<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>1.3.0version>
dependency>

3、配置SpringBoot支持MyBatis

mybatis:
  mapper-locations: classpath*:mapper/*.xml
  type-aliases-package: com.tenghu.sbm

4、实体类

/**
 * 客户基础信息
 * @author Arvin
 * @date 2017/12/9 12:14
 */
@Api(value = "客户基础信息",description = "客户基础信息")
@Alias(value = "CusBaseInfo")
public class CusBaseInfo {
    @ApiModelProperty(value = "客户ID",name = "cusId",dataType = "String",readOnly = true)
    private String cusId;
    @ApiModelProperty(value = "客户编码",name = "cusCode",dataType = "String",required = true,readOnly = true)
    private String cusCode;
    @ApiModelProperty(value = "客户名称",name = "cusName",dataType = "String",required = true,readOnly = true)
    private String cusName;
    @ApiModelProperty(value = "客户简称",name = "cusAbbr",dataType = "String")
    private String cusAbbr;
    @ApiModelProperty(value = "客户地址",name = "address",dataType = "String")
    private String address;

    public CusBaseInfo() {
    }

    public CusBaseInfo(String cusId, String cusCode, String cusName, String cusAbbr, String address) {
        this.cusId = cusId;
        this.cusCode = cusCode;
        this.cusName = cusName;
        this.cusAbbr = cusAbbr;
        this.address = address;
    }
    //省略get和set方法
}

5、创建Mapper接口

/**
 * 客户基础信息数据操作接口
 * @author Arvin
 * @date 2017/12/9 12:17
 */
@Mapper
public interface CusBaseInfoMapper {
    /**
     * 获取所有客户信息
     * @return
     */
    List getAllCusBaseInfo();

    /**
     * 保存客户基础信息
     * @param cusBaseInfo 客户基础信息
     * @return
     */
    int saveCusBaseInfo(CusBaseInfo cusBaseInfo);

    /**
     * 根据客户ID获取客户基础信息
     * @param cusId 客户ID
     * @return
     */
    CusBaseInfo getCusBaseInfoById(String cusId);

    /**
     * 根据客户名称获取客户基础信息
     * @param cusName 客户名称
     * @return
     */
    CusBaseInfo getCusBaseInfoByName(String cusName);

    /**
     * 修改客户基础信息
     * @param cusBaseInfo 客户基础信息
     * @return
     */
    int updateCusBaseInfo(CusBaseInfo cusBaseInfo);

    /**
     * 根据客户ID删除客户信息
     * @param cusId 客户ID
     * @return
     */
    int deleteCusBaseInfo(String cusId);

    /**
     * 批量删除客户信息
     * @param cusIds 客户ID
     * @return
     */
    int deleteBatchCusBaseInfo(String[] cusIds);
}

这里需要注意必须加上@Mapper的注解,不然@Autowired将注入失败

6、创建Mapper XML映射文件

我的xml文件创建到maven的resources下的。



<mapper namespace="com.tenghu.sbm.cus.mapper.CusBaseInfoMapper">
    
    <resultMap id="cus_base_info" type="CusBaseInfo">
        <id column="cus_id" property="cusId" javaType="String">id>
        <result column="cus_code" property="cusCode" javaType="String"/>
        <result column="cus_name" property="cusName" javaType="String"/>
        <result column="cus_abbr" property="cusAbbr" javaType="String"/>
        <result column="address" property="address" javaType="String"/>
    resultMap>

    
    <sql id="sql_tab">cus_base_infosql>

    
    <sql id="sql_select_all">select * from sql>

    
    <select id="getAllCusBaseInfo" resultMap="cus_base_info">
        <include refid="sql_select_all"/>
        <include refid="sql_tab"/>
    select>

    
    <insert id="saveCusBaseInfo" parameterType="CusBaseInfo">
        <selectKey keyProperty="cusId" order="BEFORE" resultType="String">
            select replace(uuid(),'-','')
        selectKey>
        insert into cus_base_info(cus_id,cus_code,cus_name,cus_abbr,address) values(#{cusId},#{cusCode},#{cusName},#{cusAbbr},#{address})
    insert>

    
    <select id="getCusBaseInfoById" resultMap="cus_base_info">
        <include refid="sql_select_all"/>
        <include refid="sql_tab"/>
        <where>cus_id = #{cusId}where>
    select>

    
    <select id="getCusBaseInfoByName" resultMap="cus_base_info">
        <include refid="sql_select_all"/>
        <include refid="sql_tab"/>
        <where>cus_name = #{cusName}where>
    select>

    
    <update id="updateCusBaseInfo" parameterType="CusBaseInfo">
        update <include refid="sql_tab"/>
        <set>
            cus_id = #{cusId}
            <if test="null!=cusCode and ''!=cusCode">,cus_code=#{cusCode}if>
            <if test="null!=cusName and ''!=cusName">,cus_name=#{cusName}if>
            <if test="null!=cusAbbr and ''!=cusAbbr">,cus_abbr=#{cusAbbr}if>
            <if test="null!=address and ''!=address">,address=#{address}if>
        set>
        <where>
            cus_id=#{cusId}
        where>
    update>

    
    <delete id="deleteCusBaseInfo" parameterType="String">
        delete from <include refid="sql_tab"/>
        <where>
            cus_id=#{cusId}
        where>
    delete>

    
    <delete id="deleteBatchCusBaseInfo" parameterType="String">
       delete from <include refid="sql_tab"/>
        <where>
            cus_id in
            <foreach collection="array" item="cusId" open="(" separator="," close=")">
                #{cusId}
            foreach>
        where>
    delete>
mapper>

到这里就已经整合好了。下面创建服务层。

7、创建Service与实现

/**
 * 客户基础信息服务接口
 * @author Arvin
 * @date 2017/12/9 12:35
 */
public interface CusBaseInfoService {
    /**
     * 获取所有客户基础信息
     * @return
     */
    RestResponse getAllCusBaseInfo();

    /**
     * 保存客户基础信息
     * @param cusBaseInfo 客户基础信息
     * @return
     */
    RestResponse saveCusBaseInfo(CusBaseInfo cusBaseInfo);

    /**
     * 根据客户ID获取客户基础信息
     * @param cusId 客户ID
     * @return
     */
    RestResponse getCusBaseInfoById(String cusId);

    /**
     * 修改客户基础信息
     * @param cusBaseInfo 客户基础信息
     * @return
     */
    RestResponse updateCusBaseInfo(CusBaseInfo cusBaseInfo);

    /**
     * 根据客户ID删除客户信息
     * @param cusId 客户ID
     * @return
     */
    RestResponse deleteCusBaseInfo(String cusId);

    /**
     * 批量删除客户信息
     * @param cusIds 客户ID
     * @return
     */
    RestResponse deleteBatchCusBaseInfo(String[] cusIds);
}

/**
 * 客户基础信息服务实现类
 * @author Arvin
 * @date 2017/12/9 12:37
 */
@Service
public class CusBaseInfoServiceImpl implements CusBaseInfoService{

    @Autowired
    private CusBaseInfoMapper cusBaseInfoMapper;

    @Override
    public RestResponse getAllCusBaseInfo() {
        return RestResponseFactory.getSucResponse(cusBaseInfoMapper.getAllCusBaseInfo());
    }

    @Override
    public RestResponse saveCusBaseInfo(CusBaseInfo cusBaseInfo) {
        //根据客户名称获取客户信息
        CusBaseInfo oldCusBaseInfo=cusBaseInfoMapper.getCusBaseInfoByName(cusBaseInfo.getCusName());
        if(null!=oldCusBaseInfo){
            return RestResponseFactory.getErrorResponse("客户【"+cusBaseInfo.getCusName()+"】已存在!");
        }
        //保存客户信息
        int result=cusBaseInfoMapper.saveCusBaseInfo(cusBaseInfo);
        if(result>0){
            return RestResponseFactory.getSucResponse(cusBaseInfo);
        }
        return RestResponseFactory.getErrorResponse("客户【"+cusBaseInfo.getCusName()+"】保存失败!");
    }

    @Override
    public RestResponse getCusBaseInfoById(String cusId) {
        return RestResponseFactory.getSucResponse(cusBaseInfoMapper.getCusBaseInfoById(cusId));
    }

    @Override
    public RestResponse updateCusBaseInfo(CusBaseInfo cusBaseInfo) {
        //检查客户是否存在
        CusBaseInfo oldCusBaseInfo=cusBaseInfoMapper.getCusBaseInfoById(cusBaseInfo.getCusId());
        if(null==oldCusBaseInfo){
            return RestResponseFactory.getErrorResponse("客户【"+cusBaseInfo.getCusName()+"】不存在!");
        }
        //更新客户信息
        int result=cusBaseInfoMapper.updateCusBaseInfo(cusBaseInfo);
        if(result>0){
            return RestResponseFactory.getSucResponse("更新成功!");
        }
        return RestResponseFactory.getErrorResponse("更新失败!");
    }

    @Override
    public RestResponse deleteCusBaseInfo(String cusId) {
        int result=cusBaseInfoMapper.deleteCusBaseInfo(cusId);
        return result>0?RestResponseFactory.getSucResponse("删除成功!"):RestResponseFactory.getErrorResponse("删除失败!");
    }

    @Override
    public RestResponse deleteBatchCusBaseInfo(String[] cusIds) {
        int result=cusBaseInfoMapper.deleteBatchCusBaseInfo(cusIds);
        return result>0?RestResponseFactory.getSucResponse("删除成功!"):RestResponseFactory.getErrorResponse("删除失败!");
    }
}

这里的service层的接口返回参数都为RestResponse 类,该类的作用是统一处理消息结果。通常在开发接口时都需要返回消息CODE,消息内容及数据这些信息,如果每个接口都写一遍,除了浪费时间,代码也不美观。

8、启动查看效果

SpringBoot整合MyBatis_第1张图片
上面说到返回接口信息统一,如下:
SpringBoot整合MyBatis_第2张图片
其他接口都是都有status、message、data这三个参数,当然了如果data为空,在返回结果里面就不会出现,这里需要配置SpringBoot在序列化结果时忽略为空的字段。配置如下:

spring:
  jackson:
    default-property-inclusion: non_null

这里的代码没有放出Controller类,如需要查看完整的结果实例可查看:SpringBoot整合MyBatis

你可能感兴趣的:(spring-boot,springboot,mybatis)