在【SpringBoot攻略二、Hello World实战】基础上追加...
1、pom.xml引入依赖
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.0
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.5
com.alibaba
druid-spring-boot-starter
1.1.9
mysql
mysql-connector-java
5.1.38
com.alibaba
fastjson
1.2.58
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配置
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 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 getIdList() {
return idList;
}
public void setIdList(List 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 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 getYwIdList() {
return ywIdList;
}
public void setYwIdList(List 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 {
/**
* 根据id获取数据
* @param id
* @return
*/
public T findById(String id);
/**
* 根据自定义条件获取数据
*
* 不处理对象属性为null和""的情况
* @param entity
* @return
*/
public List findAll(T entity);
/**
* 新增
* @param entity
*/
public void save(T entity);
/**
* 批量新增
*
* 注意:sql文本有长度限制
* @param list
*/
public void batchSave(@Param("list") List 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 list);
/**
* 根据id批量更新
*
* 处理对象属性为null和""的情况
* @param list
*/
public void batchUpdateByIdWithNull(@Param("list") List list);
/**
* 根据idList批量更新
*
* 不处理对象属性为null和""的情况
* @param entity
*/
public void updateByIds(T entity);
/**
* 自定义更新
*
* 说明:set更新字段key:set_表字段名,where条件字段key:where_表字段名
* @param map
*/
public void updateByCondition(@Param("map") Map map);
/**
* 根据id删除
* @param id
*/
public void deleteById(String id);
/**
* 根据idList批量删除
* @param idList
*/
public void deleteByIds(@Param("idList") List 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 {
}
src/main/resources创建xml配置sql
mybatis/common/CommonfileMapper.xml
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
id, name, size, path, type, yw_id
#{id}, #{name}, #{size}, #{path}, #{type}, #{ywId}
#{item.id}, #{item.name}, #{item.size}, #{item.path}, #{item.type}, #{item.ywId}
insert into t_c_file( )
values( )
insert into t_c_file( )
values
( )
update t_c_file
name = #{name},
size = #{size},
path = #{path},
type = #{type},
yw_id = #{ywId},
where id = #{id}
update t_c_file
name = #{name},
name = null,
size = #{size},
size = null,
path = #{path},
path = null,
type = #{type},
type = null,
yw_id = #{ywId},
yw_id = null,
where id = #{id}
update t_c_file
name = #{name},
size = #{size},
path = #{path},
type = #{type},
yw_id = #{ywId},
where id = #{id}
update t_c_file
name = #{name},
name = null,
size = #{size},
size = null,
path = #{path},
path = null,
type = #{type},
type = null,
yw_id = #{ywId},
yw_id = null,
where id = #{id}
update t_c_file
name = #{name},
size = #{size},
path = #{path},
type = #{type},
yw_id = #{ywId},
where id in
#{item}
update t_c_file
${item} = #{map[${item}]},
${item} = null,
and ${item} = #{map[${item}]}
and ${item} is null
or 1 != 1
delete from t_c_file
where id = #{id}
delete from t_c_file
where id in
#{item}
delete a from t_c_file a
and id = #{id}
and name = #{name}
and size = #{size}
and path = #{path}
and type = #{type}
and yw_id = #{ywId}
and yw_id in
#{item}
or 1 != 1
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 {
public T findById(String id);
public PageInfo findByPage(T entity);
public List 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> implements BaseService {
@Autowired
protected Dao dao;
@Override
public T findById(String id) {
return dao.findById(id);
}
@Override
public PageInfo findByPage(T entity) {
PageHelper.startPage(entity.getPageIndex(), entity.getPageSize());
List entityList = dao.findAll(entity);
return new PageInfo(entityList);
}
@Override
public List 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{
}
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 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> {
@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 findByPage(@RequestBody T entity, HttpServletRequest request, HttpServletResponse response) {
return service.findByPage(entity);
}
@RequestMapping(value="findAll", method=RequestMethod.POST)
public List 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 {
}
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 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,整合完了!