SpringBoot攻略六、集成mybatis实战

在【SpringBoot攻略二、Hello World实战】基础上追加...

1、pom.xml引入依赖

    <!-- spring boot mybatis -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.0</version>
    </dependency>
    
    <!-- mybatis 分页插件pagehelper -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.5</version>
    </dependency>

    <!-- Druid database connection pool -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.9</version>
    </dependency>
    
    <!-- mysql -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    
    <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.58</version>
    </dependency>

2、application.properties配置

    #多环境配置,指定加载的环境(开发、测试、生产),yml同理
    #命名规则:application-{profile}.properties
    spring.profiles.active=dev
    
    
    #mybatis-------------------------------------------------------------------
    mybatis.configLocation=classpath:mybatis/mybatis-config.xml
    mybatis.mapperLocations=classpath*:/mybatis/**/*Mapper.xml
    #用类名表示此类全限定名的别名,不支持通配符*,可以修改源码支持*
    mybatis.typeAliasesPackage=com.javasgj.springboot.ssm.domain
    #mybatis分页插件pagehelper
    pagehelper.helperDialect=mysql
    pagehelper.reasonable=true
    pagehelper.supportMethodsArguments=true
    pagehelper.autoRuntimeDialect=true
    pagehelper.params=count=countSql

说明:这些配置项可以在mybatis-spring-boot-autoconfigure-2.0.0.jar中的MybatisAutoConfiguration、MybatisProperties找到,
记住:配置其他组件都是按照同样的规则去找配置项!

3、application-dev.properties配置

#开发环境


#server,内嵌tomcat配置信息
#端口,默认值8080
server.port=8080
#应用上下文,默认值/
server.servlet.contextPath=/springboot


#druid dataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/cs?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#配置初始化大小、最小、最大
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
#配置从连接池获取连接等待超时的时间
spring.datasource.druid.maxWait=60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
#配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.minEvictableIdleTimeMillis=300000
#检验连接是否有效的查询语句
spring.datasource.druid.validationQuery=select 1
#设置从连接池获取连接时是否检查连接有效性,true时,如果连接空闲时间超过minEvictableIdleTimeMillis进行检查,否则不检查;false时,不检查
spring.datasource.druid.testWhileIdle=true
#设置从连接池获取连接时是否检查连接有效性,true时,每次都检查;false时,不检查
spring.datasource.druid.testOnBorrow=false
#设置往连接池归还连接时是否检查连接有效性,true时,每次都检查;false时,不检查
spring.datasource.druid.testOnReturn=false
#配置监控统计拦截的filters
spring.datasource.druid.filters=stat,slf4j
#打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20

数据库脚本:
创建数据库

create database cs default character set utf8 collate utf8_general_ci;

创建公共附件表

create table t_c_file  (
      id varchar(50) NOT NULL COMMENT '主键',
      name varchar(200) NULL COMMENT '文件名称',
      size int NULL COMMENT '文件大小',
      path varchar(200) NULL COMMENT '文件路径',
      type varchar(50) NULL COMMENT '文件类型',
      yw_id varchar(50) NULL COMMENT '业务id',
      cjr_id varchar(50) NULL COMMENT '创建人id',
      cjr varchar(50) NULL COMMENT '创建人',
      cj_sj datetime NULL COMMENT '创建时间',
      gxr_id varchar(50) NULL COMMENT '更新人id',
      gxr varchar(50) NULL COMMENT '更新人',
      gx_sj datetime NULL COMMENT '更新时间',
      PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4、mybatis-config.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>  
        <!-- 全局映射器启用缓存 -->  
        <setting name="cacheEnabled" value="true"/>  
        
        <!-- 查询时,关闭关联对象即时加载以提高性能 -->  
        <setting name="lazyLoadingEnabled" value="false"/>  
  
        <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->  
        <setting name="multipleResultSetsEnabled" value="true"/>  
  
        <!-- 允许使用列标签代替列名 -->  
        <setting name="useColumnLabel" value="true"/>  
  
        <!-- 不允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->  
        <setting name="useGeneratedKeys" value="true"/>  
  
        <!-- 给予被嵌套的resultMap以字段-属性的映射支持 FULL,PARTIAL -->  
        <setting name="autoMappingBehavior" value="PARTIAL"/>  
  
        <!-- 对于批量更新操作缓存SQL以提高性能 BATCH,SIMPLE -->  
        <!-- <setting name="defaultExecutorType" value="BATCH" /> -->  
  
        <!-- 数据库超过25000秒仍未响应则超时 -->  
        <!-- <setting name="defaultStatementTimeout" value="25000" /> -->  
  
        <!-- Allows using RowBounds on nested statements -->  
        <setting name="safeRowBoundsEnabled" value="false"/>  
  
        <!-- 驼峰命名法映射字段和类型属性. -->  
        <setting name="mapUnderscoreToCamelCase" value="true"/>  
  
        <!-- MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT   
            local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession. -->  
        <setting name="localCacheScope" value="SESSION"/>  
  
        <!-- Specifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers require specifying the column JDBC type but others work with generic values   
            like NULL, VARCHAR or OTHER. -->  
        <setting name="jdbcTypeForNull" value="VARCHAR"/>  
  
        <!-- Specifies which Object's methods trigger a lazy load -->  
        <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>  
  
        <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->  
        <setting name="aggressiveLazyLoading" value="false"/>  
  
        <!-- 日志实现 -->
        <setting name="logImpl" value="SLF4J" />
    </settings>
</configuration>

5、创建实体类

package com.javasgj.springboot.ssm.domain;

import com.alibaba.fastjson.annotation.JSONField;

/**
 * 分页工具类
 */
public class Pagination {

    /**
     * 当前页码
     */
    @JSONField(serialize = false)
    protected int pageIndex;
    
    /**
     * 每页大小
     */
    @JSONField(serialize = false)
    protected int pageSize;
    
    
    public int getPageIndex() {
        return pageIndex;
    }
    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
}

BaseEntity:

package com.javasgj.springboot.ssm.domain;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.annotation.JSONField;

/**
 * 基础实体类
 */
public class BaseEntity extends Pagination {

    // 主键
    protected String id;
    @JSONField(serialize = false)
    protected List<String> idList;
    
    // 创建人
    private String cjrId;
    private String cjr;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date cjSj;
    
    // 更新人
    private String gxrId;
    private String gxr;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date gxSj;
    
    
    public String getId() {
        return id;
    }

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

    public List<String> getIdList() {
        return idList;
    }

    public void setIdList(List<String> idList) {
        this.idList = idList;
    }

    public String getCjrId() {
        return cjrId;
    }

    public void setCjrId(String cjrId) {
        this.cjrId = cjrId;
    }

    public String getCjr() {
        return cjr;
    }

    public void setCjr(String cjr) {
        this.cjr = cjr;
    }

    public Date getCjSj() {
        return cjSj;
    }

    public void setCjSj(Date cjSj) {
        this.cjSj = cjSj;
    }

    public String getGxrId() {
        return gxrId;
    }

    public void setGxrId(String gxrId) {
        this.gxrId = gxrId;
    }

    public String getGxr() {
        return gxr;
    }

    public void setGxr(String gxr) {
        this.gxr = gxr;
    }

    public Date getGxSj() {
        return gxSj;
    }

    public void setGxSj(Date gxSj) {
        this.gxSj = gxSj;
    }
}

Commonfile:

package com.javasgj.springboot.ssm.domain;

import java.util.List;

public class Commonfile extends BaseEntity {

    // 以下为实体类对应表的所有字段
    private String name;
    private Long size;
    private String path;
    private String type;
    private String ywId;
    
    // 额外辅助字段
    private List<String> ywIdList;
    
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Long getSize() {
        return size;
    }
    public void setSize(Long size) {
        this.size = size;
    }
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getYwId() {
        return ywId;
    }
    public void setYwId(String ywId) {
        this.ywId = ywId;
    }
    public List<String> getYwIdList() {
        return ywIdList;
    }
    public void setYwIdList(List<String> ywIdList) {
        this.ywIdList = ywIdList;
    }
}

6、创建Mapper
BaseMapper:

package com.javasgj.springboot.ssm.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;

import com.javasgj.springboot.ssm.domain.BaseEntity;

public interface BaseMapper<T extends BaseEntity> {
    
    /**
     * 根据id获取数据
     * @param id
     * @return
     */
    public T findById(String id);
    
    /**
     * 根据自定义条件获取数据
     * 
     * 不处理对象属性为null和""的情况
     * @param entity
     * @return
     */
    public List<T> findAll(T entity);
    
    /**
     * 新增
     * @param entity
     */
    public void save(T entity);
    
    /**
     * 批量新增
     * 
     * 注意:sql文本有长度限制
     * @param list
     */
    public void batchSave(@Param("list") List<T> list);
    
    /**
     * 根据id更新
     * 
     * 不处理对象属性为null和""的情况
     * @param entity
     */
    public void updateByIdWithoutNull(T entity);
    
    /**
     * 根据id更新
     * 
     * 处理对象属性为null和""的情况
     * @param entity
     */
    public void updateByIdWithNull(T entity);
    
    /**
     * 根据id批量更新
     * 
     * 不处理对象属性为null和""的情况
     * @param list
     */
    public void batchUpdateByIdWithoutNull(@Param("list") List<T> list);
    
    /**
     * 根据id批量更新
     * 
     * 处理对象属性为null和""的情况
     * @param list
     */
    public void batchUpdateByIdWithNull(@Param("list") List<T> list);
    
    /**
     * 根据idList批量更新
     * 
     * 不处理对象属性为null和""的情况
     * @param entity
     */
    public void updateByIds(T entity);
    
    /**
     * 自定义更新
     * 
     * 说明:set更新字段key:set_表字段名,where条件字段key:where_表字段名
     * @param map
     */
    public void updateByCondition(@Param("map") Map<String, Object> map);
    
    /**
     * 根据id删除
     * @param id
     */
    public void deleteById(String id);
    
    /**
     * 根据idList批量删除
     * @param idList
     */
    public void deleteByIds(@Param("idList") List<String> idList);
    
    /**
     * 自定义删除
     * 
     * 不处理对象属性为null和""的情况
     * @param entity
     */
    public void deleteByCondition(T entity);
}

CommonfileMapper:

package com.javasgj.springboot.ssm.dao;

import com.javasgj.springboot.ssm.domain.Commonfile;

public interface CommonfileMapper extends BaseMapper<Commonfile> {
    
}

src/main/resources创建xml配置sql
mybatis/common/CommonfileMapper.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">

<mapper namespace="com.javasgj.springboot.ssm.dao.CommonfileMapper">

    <sql id="selectSqlId">a.id, a.name, a.size, a.path, a.type, a.yw_id, a.cjr_id, a.cjr, a.cj_sj, a.gxr_id, a.gxr, a.gx_sj</sql>
    <sql id="insertSqlId">id, name, size, path, type, yw_id</sql>
    <sql id="insertValSqlId">#{id}, #{name}, #{size}, #{path}, #{type}, #{ywId}</sql>
    <sql id="insertBatchValSqlId">#{item.id}, #{item.name}, #{item.size}, #{item.path}, #{item.type}, #{item.ywId}</sql>


    <select id="findById" resultType="Commonfile">
        select <include refid="selectSqlId"></include>
        from t_c_file a
        where a.id = #{id}
    </select>

    <select id="findAll" parameterType="Commonfile" resultType="Commonfile">
        select <include refid="selectSqlId"></include>
        from t_c_file a
        <where>
            <if test="id != null and id != ''">
                and a.id = #{id}
            </if>
            <if test="name != null and name != ''">
                and a.name like concat('%', #{name}, '%')
            </if>
            <if test="size != null and size != ''">
                and a.size = #{size}
            </if>
            <if test="path != null and path != ''">
                and a.path like concat('%', #{path}, '%')
            </if>
            <if test="type != null and type != ''">
                and a.type = #{type}
            </if>
            <if test="ywId != null and ywId != ''">
                and a.yw_id = #{ywId}
            </if>
            <if test="cjrId != null and cjrId != ''">
                and a.cjr_id = #{cjrId}
            </if>
            <if test="cjr != null and cjr != ''">
                and a.cjr = #{cjr}
            </if>
            <if test="cjSj != null and cjSj != ''">
                and a.cj_sj = #{cjSj}
            </if>
            <if test="gxrId != null and gxrId != ''">
                and a.gxr_id = #{gxrId}
            </if>
            <if test="gxr != null and gxr != ''">
                and a.gxr = #{gxr}
            </if>
            <if test="gxSj != null and gxSj != ''">
                and a.gx_sj = #{gxSj}
            </if>
        </where>
        order by a.cj_sj desc
    </select>

    <insert id="save" parameterType="Commonfile">
        insert into t_c_file(<include refid="insertSqlId"></include>)
        values(<include refid="insertValSqlId"></include>)
    </insert>

    <insert id="batchSave" parameterType="arraylist">
        insert into t_c_file(<include refid="insertSqlId"></include>)
        values
        <foreach collection="list" item="item" index="index" separator="," >
            (<include refid="insertBatchValSqlId"></include>)
        </foreach>
    </insert>

    <update id="updateByIdWithoutNull" parameterType="Commonfile">
        update t_c_file
        <trim prefix="set" suffixOverrides=",">
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="size != null and size != ''">
                size = #{size},
            </if>
            <if test="path != null and path != ''">
                path = #{path},
            </if>
            <if test="type != null and type != ''">
                type = #{type},
            </if>
            <if test="ywId != null and ywId != ''">
                yw_id = #{ywId},
            </if>
        </trim>
        where id = #{id}
    </update>

    <update id="updateByIdWithNull" parameterType="Commonfile">
        update t_c_file
        <trim prefix="set" suffixOverrides=",">
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="name == null or name == ''">
                name = null,
            </if>
            <if test="size != null and size != ''">
                size = #{size},
            </if>
            <if test="size == null or size == ''">
                size = null,
            </if>
            <if test="path != null and path != ''">
                path = #{path},
            </if>
            <if test="path == null or path == ''">
                path = null,
            </if>
            <if test="type != null and type != ''">
                type = #{type},
            </if>
            <if test="type == null or type == ''">
                type = null,
            </if>
            <if test="ywId != null and ywId != ''">
                yw_id = #{ywId},
            </if>
            <if test="ywId == null or ywId == ''">
                yw_id = null,
            </if>
        </trim>
        where id = #{id}
    </update>

    <update id="batchUpdateByIdWithoutNull" parameterType="arraylist">
        <foreach collection="list" item="item"  separator=";">
            update t_c_file
            <trim prefix="set" suffixOverrides=",">
                <if test="name != null and name != ''">
                    name = #{name},
                </if>
                <if test="size != null and size != ''">
                    size = #{size},
                </if>
                <if test="path != null and path != ''">
                    path = #{path},
                </if>
                <if test="type != null and type != ''">
                    type = #{type},
                </if>
                <if test="ywId != null and ywId != ''">
                    yw_id = #{ywId},
                </if>
            </trim>
            where id = #{id}
        </foreach>
    </update>

    <update id="batchUpdateByIdWithNull" parameterType="arraylist">
        <foreach collection="list" item="item"  separator=";">
            update t_c_file
            <trim prefix="set" suffixOverrides=",">
                <if test="name != null and name != ''">
                    name = #{name},
                </if>
                <if test="name == null or name == ''">
                    name = null,
                </if>
                <if test="size != null and size != ''">
                    size = #{size},
                </if>
                <if test="size == null or size == ''">
                    size = null,
                </if>
                <if test="path != null and path != ''">
                    path = #{path},
                </if>
                <if test="path == null or path == ''">
                    path = null,
                </if>
                <if test="type != null and type != ''">
                    type = #{type},
                </if>
                <if test="type == null or type == ''">
                    type = null,
                </if>
                <if test="ywId != null and ywId != ''">
                    yw_id = #{ywId},
                </if>
                <if test="ywId == null or ywId == ''">
                    yw_id = null,
                </if>
            </trim>
            where id = #{id}
        </foreach>
    </update>

    <update id="updateByIds" parameterType="Commonfile">
        update t_c_file
        <trim prefix="set" suffixOverrides=",">
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="size != null and size != ''">
                size = #{size},
            </if>
            <if test="path != null and path != ''">
                path = #{path},
            </if>
            <if test="type != null and type != ''">
                type = #{type},
            </if>
            <if test="ywId != null and ywId != ''">
                yw_id = #{ywId},
            </if>
        </trim>
        where id in
        <foreach collection="idList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
    </update>

    <update id="updateByCondition" parameterType="hashmap">
        update t_c_file
        <trim prefix="set" suffixOverrides=",">
            <foreach collection="map.keys" item="item">
                <if test='item.indexOf("set_") == 0'>
                    <if test="map[item] != null and map[item] != ''">
                        <trim prefixOverrides="set_">${item}</trim> = #{map[${item}]},
                    </if>
                    <if test="map[item] == null or map[item] == ''">
                        <trim prefixOverrides="set_">${item}</trim> = null,
                    </if>
                </if>
            </foreach>
        </trim>
        <where>
            <foreach collection="map.keys" item="item">
                <if test='item.indexOf("where_") == 0'>
                    <if test="map[item] != null and map[item] != ''">
                        and <trim prefixOverrides="set_">${item}</trim> = #{map[${item}]}
                    </if>
                    <if test="map[item] == null or map[item] == ''">
                        and <trim prefixOverrides="set_">${item}</trim> is null
                    </if>
                </if>
            </foreach>
            or 1 != 1
        </where>
    </update>

    <delete id="deleteById">
        delete from t_c_file
        where id = #{id}
    </delete>

    <delete id="deleteByIds" parameterType="arraylist">
        delete from t_c_file
        where id in
        <foreach collection="idList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
    </delete>

    <delete id="deleteByCondition" parameterType="Commonfile">
        delete a from t_c_file a
        <where>
            <if test="id != null and id != ''">
                and id = #{id}
            </if>
            <if test="name != null and name != ''">
                and name = #{name}
            </if>
            <if test="size != null and size != ''">
                and size = #{size}
            </if>
            <if test="path != null and path != ''">
                and path = #{path}
            </if>
            <if test="type != null and type != ''">
                and type = #{type}
            </if>
            <if test="ywId != null and ywId != ''">
                and yw_id = #{ywId}
            </if>
            <if test="ywIdList != null and ywIdList.size > 0">
                and yw_id in
                <foreach collection="ywIdList" item="item" open="(" close=")" separator=",">
                    #{item}
                </foreach>
            </if>
            or 1 != 1
        </where>
    </delete>
</mapper>

7、创建service
BaseService:

package com.javasgj.springboot.ssm.service;

import java.util.List;

import com.github.pagehelper.PageInfo;
import com.javasgj.springboot.ssm.domain.BaseEntity;

public interface BaseService<T extends BaseEntity> {
    
    public T findById(String id);
    
    public PageInfo<T> findByPage(T entity);
    
    public List<T> findAll(T entity);
    
    public void save(T entity);
    
    public void update(T entity);
    
    public void deleteById(String id);
}

BaseServiceImpl:

package com.javasgj.springboot.ssm.service;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

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

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javasgj.springboot.ssm.dao.BaseMapper;
import com.javasgj.springboot.ssm.domain.BaseEntity;
import com.javasgj.springboot.ssm.utils.StringUtil;

public abstract class BaseServiceImpl<T extends BaseEntity, Dao extends BaseMapper<T>> implements BaseService<T> {
    
    @Autowired
    protected Dao dao;

    @Override
    public T findById(String id) {
        return dao.findById(id);
    }
    
    @Override
    public PageInfo<T> findByPage(T entity) {
        PageHelper.startPage(entity.getPageIndex(), entity.getPageSize());
        List<T> entityList = dao.findAll(entity);
        return new PageInfo<T>(entityList);
    }
    
    @Override
    public List<T> findAll(T entity) {
        return dao.findAll(entity);
    }

    @Override
    @Transactional
    public void save(T entity) {
        entity.setId(UUID.randomUUID().toString().replace("-", ""));
        dao.save(entity);
    }

    @Override
    @Transactional
    public void update(T entity) {
        dao.updateByIdWithNull(entity);
    }

    @Override
    @Transactional
    public void deleteById(String id) {
        if(!StringUtil.isEmpty(id)) {
            String[] a = id.split(",");
            dao.deleteByIds(Arrays.asList(a));
        }
    }
}

CommonfileService:

package com.javasgj.springboot.ssm.service;

import com.javasgj.springboot.ssm.domain.Commonfile;

public interface CommonfileService extends BaseService<Commonfile>{

}

CommonfileServiceImpl:

package com.javasgj.springboot.ssm.service;

import org.springframework.stereotype.Service;

import com.javasgj.springboot.ssm.dao.CommonfileMapper;
import com.javasgj.springboot.ssm.domain.Commonfile;

@Service
public class CommonfileServiceImpl extends BaseServiceImpl<Commonfile, CommonfileMapper> implements CommonfileService {

}

8、创建Controller
BaseController:

package com.javasgj.springboot.ssm.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.github.pagehelper.PageInfo;
import com.javasgj.springboot.ssm.domain.BaseEntity;
import com.javasgj.springboot.ssm.service.BaseService;

/**
 * 基础模块,封装基本的CURD操作
 */
public class BaseController<T extends BaseEntity, Service extends BaseService<T>> {

    @Autowired
    protected Service service;
    
    @RequestMapping(value="findById", method=RequestMethod.GET)
    public T findById(String id, HttpServletRequest request, HttpServletResponse response) {
        return service.findById(id);
    }

    @RequestMapping(value="findByPage", method=RequestMethod.POST)
    public PageInfo<T> findByPage(@RequestBody T entity, HttpServletRequest request, HttpServletResponse response) {
        return service.findByPage(entity);
    }
    
    @RequestMapping(value="findAll", method=RequestMethod.POST)
    public List<T> findAll(@RequestBody T entity, HttpServletRequest request, HttpServletResponse response) {
        return service.findAll(entity);
    }

    @RequestMapping(value="save", method=RequestMethod.POST)
    public void save(@RequestBody T entity, HttpServletRequest request, HttpServletResponse response) {
        service.save(entity);
    }

    @RequestMapping(value="update", method=RequestMethod.POST)
    public void update(@RequestBody T entity, HttpServletRequest request, HttpServletResponse response) {
        service.update(entity);
    }
    
    @RequestMapping(value="deleteById", method=RequestMethod.POST)
    public void deleteById(@RequestBody T entity, HttpServletRequest request, HttpServletResponse response) {
        service.deleteById(entity.getId());
    }   
}

CommonfileController:

package com.javasgj.springboot.ssm.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javasgj.springboot.ssm.domain.Commonfile;
import com.javasgj.springboot.ssm.service.CommonfileService;

/**
 * 公共附件管理模块
 */
@RestController
@RequestMapping("/commonfile")
public class CommonfileController extends BaseController<Commonfile, CommonfileService> {
    
}

9、创建工具类

package com.javasgj.springboot.ssm.utils;

/**
 * 字符串工具类
 */
public class StringUtil {

    /**
     * 判断字符串是否为空
     */
    public static boolean isEmpty(String s) {
        if(s == null || "".equals(s)) {
            return true;
        }
        
        return false;
    }
}

10、应用启动类

package com.javasgj.springboot.ssm;

import java.util.ArrayList;
import java.util.List;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

/**
 * spring boot应用启动类
 * @MapperScan:mybatis Mapper接口扫描,如果不加此注解,那么必须在Mapper接口上加@Mapper
 */
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.javasgj.springboot.ssm.**.dao")
public class Application {
    
    public static void main(String[] args) {
        
        SpringApplication.run(Application.class, args);
    }
    
    /**
     * fastjson替换默认的jackjson(springmvc)
     * @return
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue, 
                                            SerializerFeature.WriteNullListAsEmpty);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);

        // 处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        
        HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
        return new HttpMessageConverters(converter);
    }
}

11、测试,使用postman
findById:
get方式:http://127.0.0.1:8080/springboot/commonfile/findById?id=6ff2a63a45da4f27bdd8f292c3b24c27

findByPage:
post方式:http://127.0.0.1:8080/springboot/commonfile/findByPage
Headers头添加:Content-Type:application/json
Body中选择raw:{"pageIndex": "1", "pageSize": "2"}

findAll:
post方式:http://127.0.0.1:8080/springboot/commonfile/findAll
Headers头添加:Content-Type:application/json
Body中选择raw:{"name": "86"}

save:
post方式:http://127.0.0.1:8080/springboot/commonfile/save
Headers头添加:Content-Type:application/json
Body中选择raw:{"name": "86"}

update:
post方式:http://127.0.0.1:8080/springboot/commonfile/update
Headers头添加:Content-Type:application/json
Body中选择raw:{"id":"0e821cf5423a4877899a1649a6de650e", "name": "86111"}

deleteById:
post方式:http://127.0.0.1:8080/springboot/commonfile/deleteById
Headers头添加:Content-Type:application/json
Body中选择raw:{"id":"0e821cf5423a4877899a1649a6de650e,57bb99851d9947208569540d28c1c453"}

OK,整合完了!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354