spring-boot(其二)

springboot整合第三方框架

(1)整合mybatis
①引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zs</groupId>
    <artifactId>springBootTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springBootTest</name>
    <description>springBootTest</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>repMaven.mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
        <dependency>
            <groupId>repMaven.org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>repMaven.junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--引入swagger2依赖-->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.1.RELEASE</version>
        </dependency>
        <!--图形化依赖-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
​
        <!--mybatis和springboot整合的jar.-->
​
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
​
</project>
​
②配置文件
spring.application.name=springBootTest
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/rom?serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=xxxx
#配置mybatis映射文件的路径
mybatis.mapper-locations=classpath:mapper/*.xml
③实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "用户信息数据")
public class User {
    @ApiModelProperty(value = "用户编号")
    private Integer userid;
    @ApiModelProperty(value = "用户名字")
    private String uname;
    @ApiModelProperty(value = "用户年龄")
    private Integer age;
}
④dao类
public interface UserDao {
   int insert(User user);
   int delete(Integer id);
   int update(User user);
   User selectById(Integer id);
   List<User> selectAll();
}
⑤mapper类
<?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.zs.dao.UserDao">
​
​
    <insert id="insert" parameterType="com.zs.entity.User">
        insert into  r_user(uname,age) values(#{uname},#{age})
    </insert>
    <delete id="delete" parameterType="java.lang.Integer">
        delete from r_user where userid=#{userid}
    </delete>
    <update id="update" parameterType="com.zs.entity.User">
        update r_user set uname=#{uname},age=#{age} where userid=#{userid}
    </update>
    <select id="selectById" parameterType="java.lang.Integer" resultType="com.zs.entity.User">
        select * from r_user where userid=#{userid}
    </select>
    <select id="selectAll" resultType="com.zs.entity.User">
        select * from r_user
    </select>
</mapper>
​
⑥service层
public interface UserService {
    R delete(Integer id);
​
    R insert(User user);
​
    R update(User user);
​
    R selectById(Integer id);
​
    R selectAll();
​
}
​
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
​
    @Override
    public R delete(Integer id) {
        int i = userDao.delete(id);
        if (i > 0) {
            return new R(200, "删除成功", null);
        } else {
            return new R(500, "删除失败", null);
        }
    }
​
    @Override
    public R insert(User user) {
        int insert = userDao.insert(user);
        if (insert > 0) {
            return new R(200, "添加成功", null);
        } else {
            return new R(500, "添加失败", null);
        }
    }
​
    @Override
    public R update(User user) {
        int update = userDao.update(user);
        if (update > 0) {
            return new R(200, "修改成功", null);
        } else {
            return new R(500, "修改失败", null);
        }
    }
​
    @Override
    public R selectById(Integer id) {
        User user = userDao.selectById(id);
        if (user != null) {
            return new R(200, "查询成功", user);
        } else {
            return new R(500, "查询失败", null);
        }
    }
​
    @Override
    public R selectAll() {
        List<User> list = userDao.selectAll();
        if (list != null) {
            return new R(200, "查询成功", list);
        } else {
            return new R(500, "查询失败", null);
        }
    }
}
​
⑦controller层
@RestController
@RequestMapping("/user")
@Api(tags = "用户信息处理表")
public class UserController {
    @Autowired
​
    private UserService userService;
    @ApiOperation(value = "删除用户信息")
    @DeleteMapping("/delete")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id" ,value = "用户编号",required = true,dataType ="int")
    )
    public R delete(Integer id){
        return userService.delete(id);
    }
​
    @GetMapping("/insert")
    @ApiOperation(value = "添加用户信息")
    public R insert(@RequestBody User user){
        return userService.insert(user);
    }
​
    @PutMapping("/update")
    @ApiOperation(value = "修改用户信息")
    public R update(@RequestBody User user){
        return userService.update(user);
    }
    @GetMapping("/selectAll")
    @ApiOperation(value = "查询所有用户信息")
    public R selectAll(){
        return userService.selectAll();
    }
    @GetMapping("/selectById")
    @ApiOperation(value = "查询单个用户信息")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id" ,value = "用户编号",required = true,dataType ="int")
    )
    public R selectById(Integer id){
        return userService.selectById(id);
    }
​
​
}
​
⑧SpringBootTestApplication
@SpringBootApplication
@MapperScan("com.zs.dao")
@EnableSwagger2
public class SpringBootTestApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(SpringBootTestApplication.class, args);
    }
​
}
(2)springboot整合swagger2
①什么是swagger2:

Swagger2 是一个规范和完整的框架,用于生成、描述、调用和可视化Restful风格的web服务,现在我们使用spring boot 整合它。作用:接口的文档在线自动生成。

②引入依赖
<!--引入swagger2依赖-->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.1.RELEASE</version>
        </dependency>
        <!--图形化依赖-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
③配置文件
@Configuration
public class Swagger2 {
    //创建swagger实例
    @Bean
    public Docket docket() {
        Docket docket=
                new Docket(DocumentationType.SWAGGER_2)
                        .apiInfo(getInfo())//设置接口文档的信息
                        .select()
                        .apis(RequestHandlerSelectors.basePackage("com.zs.controller")) //指定为那些路径下得到类生成接口文档
                        .build()
                ;
​
        return docket;
    }
​
    private ApiInfo getInfo(){
        Contact DEFAULT_CONTACT = new Contact("xxx", "http://www.ldw.com", "110@qq.com");
        ApiInfo DEFAULT = new ApiInfo("用户管理系统API", "该系统中的接口专门操作用户的", "v1.0", "http://www.baidu.com",
                DEFAULT_CONTACT, "漫动作", "http://www.jd.com", new ArrayList<VendorExtension>());
        return DEFAULT;
    }
}
④开启注解
@SpringBootApplication
@MapperScan("com.zs.dao")
@EnableSwagger2
public class SpringBootTestApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(SpringBootTestApplication.class, args);
    }
​
}
⑤访问的swagger的网址:

第一种: http://localhost:8080/swagger-ui.html

第二种: http://localhost:8080/doc.html

⑥常用注解

@Api(tags=“”): 使用在接口类上,对接口类的说明

@ApiOperation(value=""):接口方法上,对接口方法的说明

@ApiImplicitParams( @ApiImplicitParam(name=“参数名”,value="参数说明",require="是否必写",dataType="数据类型") ) : 接口方法所有参数的概述

@ApiModel(value=""): 使用在实体类上,对实体类的说明

@ApiModelProperty(value=""):使用在实体类属性上,对属性的说明

(3)springboot整合定时器
①引入依赖
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>
②定时器业务类
@Configuration
public class MyQuartzConfig {
​
    //定时业务代码
    //定义定时规则
    @Scheduled(cron = "0/5 * * * * ?")
    public void show(){
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        //发生短信 或者删除oss冗余文件  或者取消订单
    }
}
③开启定时器注解驱动
@SpringBootApplication
@MapperScan("com.zs.dao")
@EnableSwagger2
@EnableScheduling
public class SpringBootTestApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(SpringBootTestApplication.class, args);
    }
​
}
④访问地址:

Cron - 在线Cron表达式生成器

(4)springboot整合mybatis-plus
①定义:

MyBatis-Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

②特点:
  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作。

  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求

  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作

  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )

  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用

  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询。

  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库

  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

③引入依赖
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.7</version>
</dependency>
④配置文件
spring.application.name=qy174-springboot-mp
​
#数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mp?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=xxxx
​
#映射文件路径
mybatis-plus.mapper-locations=classpath*:mapper/*.xml
​
#配置日志--sql日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
⑤实体类
@Data
@ApiModel(value = "员工表")
public class Workerlist implements Serializable {
    @ApiModelProperty(value = "员工编号")
    private Integer wid;
    @Size(max= 10,message="编码长度不能超过10")
    @ApiModelProperty(value = "姓名")
    @Length(max= 10,message="编码长度不能超过10")
    private String wname;
​
    @Size(max= 2,message="编码长度不能超过2")
    @ApiModelProperty(value = "性别")
    @Length(max= 2,message="编码长度不能超过2")
    private String sex;
​
    @ApiModelProperty(value = "生日")
    private Date birthday;
​
    @ApiModelProperty(value = "党员")
    private String dangyuan;
​
    @ApiModelProperty(value="入职时间")
    private Date worktime;
​
​
    @ApiModelProperty(value ="城市")
​
    private String country;
​
    @ApiModelProperty(value="所在部门")
    private Integer depid;
​
​
    @ApiModelProperty(value="头像")
    private String head;
​
    @ApiModelProperty(value = "部门")
    @TableField(exist = false)
    private Department department;
​
    private void setWid(Integer wid){
    this.wid = wid;
    }
​
    private void setWname(String wname){
    this.wname = wname;
    }
​
    private void setSex(String sex){
    this.sex = sex;
    }
​
    private void setBirthday(Date birthday){
    this.birthday = birthday;
    }
​
    private void setDangyuan(String dangyuan){
    this.dangyuan = dangyuan;
    }
​
    private void setWorktime(Date worktime){
    this.worktime = worktime;
    }
​
    private void setCountry(String country){
    this.country = country;
    }
​
    private void setDepid(Integer depid){
    this.depid = depid;
    }
​
​
    private void setHead(String head){
    this.head = head;
    }
​
    private Integer getWid(){
    return this.wid;
    }
​
    private String getWname(){
    return this.wname;
    }
​
    private String getSex(){
    return this.sex;
    }
​
    private Date getBirthday(){
    return this.birthday;
    }
    private String getDangyuan(){
    return this.dangyuan;
    }
​
    private Date getWorktime(){
    return this.worktime;
    }
​
    private String getCountry(){
    return this.country;
    }
​
    private Integer getDepid(){
    return this.depid;
    }
​
    private String getHead(){
    return this.head;
    }
​
}
​
@ApiModel(value = "部门表")
public class Department implements Serializable {
​
    @ApiModelProperty(value = "编号")
    private Integer id;
 
    @ApiModelProperty(value = "部门名称")
    private String name;
​
    @ApiModelProperty(value = "头像")
    private String head;
​
    private void setId(Integer id){
    this.id = id;
    }
​
    private void setName(String name){
    this.name = name;
    }
​
    private void setHead(String head){
    this.head = head;
    }
​
    private Integer getId(){
    return this.id;
    }
​
    private String getName(){
    return this.name;
    }
​
    private String getHead(){
    return this.head;
    }
​
}
⑥配置类
@Configuration
public class PageConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        Docket docket=
                new Docket(DocumentationType.SWAGGER_2)
                        .apiInfo(getInfo())//设置接口文档的信息
                        .select()
                        .apis(RequestHandlerSelectors.basePackage("com.zs.controller")) //指定为那些路径下得到类生成接口文档
                        .build()
                ;
​
        return docket;
    }
​
    private ApiInfo getInfo(){
        Contact DEFAULT_CONTACT = new Contact("翟帅", "http://www.ldw.com", "110@qq.com");
        ApiInfo DEFAULT = new ApiInfo("公司员工管理系统", "该系统中的接口专门操作员工的", "v1.0", "http://www.baidu.com",
                DEFAULT_CONTACT, "漫动者", "http://www.jd.com", new ArrayList<VendorExtension>());
        return DEFAULT;
    }
}
⑦dao类
@Mapper
public interface WorkerListDao extends BaseMapper<Workerlist> {
    //分页查询
    IPage<Workerlist> selectByPage(IPage<Workerlist> page, @Param("ew") Wrapper<Workerlist> queryWrapper);
}
⑧service层
public interface WorkListService {
    public R selectAll();
    public R selectByid(Integer id);
    R insert(Workerlist workerlist);
    R update(Workerlist workerlist);
    R delete(Integer id);
}
​
​
@Service
public class WorkListServiceImpl extends ServiceImpl<WorkerListDao ,Workerlist> implements WorkListService {
    @Autowired
    private WorkerListDao workerListDao;
    @Override
    public R selectAll() {
        Page<Workerlist> page=new Page<>(1,2);
        QueryWrapper<Workerlist> wrapper=new QueryWrapper<>();
        IPage<Workerlist> userPage = workerListDao.selectByPage(page, wrapper);
       return new R(200,"查询成功",userPage);
    }
​
    @Override
    public R selectByid(Integer id) {
        Workerlist workerlist = workerListDao.selectById(id);
        if (workerlist!=null){
            return new R(200,"查询成功",workerlist);
        }
        return new R(500,"查询失败",null);
    }
​
    @Override
    public R insert(Workerlist workerlist) {
        int i = workerListDao.insert(workerlist);
        if (i>0){
            return new R(200,"添加成功",null);
        }
        return new R(500,"添加失败",null);
    }
​
    @Override
    public R update(Workerlist workerlist) {
        int i = workerListDao.updateById(workerlist);
        if (i>0){
            return new R(200,"修改成功",null);
        }
        return new R(500,"修改失败",null);
    }
​
    @Override
    public R delete(Integer id) {
        int i = workerListDao.deleteById(id);
        if (i>0){
            return new R(200,"删除成功",null);
        }
        return new R(500,"删除失败",null);
    }
}
⑨mapper
<?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.zs.dao.WorkerListDao">
    <resultMap id="BaseMapping" type="com.zs.entity.Workerlist">
        <id property="wid" column="wid" javaType="java.lang.Integer"/>
        <result property="wname" column="wname" javaType="java.lang.String"/>
        <result property="sex" column="sex" javaType="java.lang.String"/>
        <result property="birthday" column="birthday" jdbcType="TIMESTAMP"/>
        <result property="dangyuan" column="dangyuan" javaType="java.lang.String"/>
        <result property="worktime" column="worktime" jdbcType="TIMESTAMP"/>
        <result property="country" column="country" javaType="java.lang.String"/>
        <result property="depid" column="depid" javaType="java.lang.Integer"/>
        <!--多对一的标签-->
        <association property="department" javaType="com.zs.entity.Department">
            <id property="id" column="id" javaType="java.lang.Integer"/>
            <result property="name" column="name" javaType="java.lang.String"/>
            <result property="head" column="head" javaType="java.lang.String"/>
        </association>
    </resultMap>
    <select id="selectByPage" resultMap="BaseMapping">
        select * from workerlist w join department d on w.depid=d.id
            ${ew.customSqlSegment}
    </select>
​
​
</mapper>
⑩controller
@RestController
@Api(tags = "员工信息处理表")
public class WorkerListController {
    @Autowired
    private WorkListService workListService;
​
​
    @GetMapping("/list")
    @ApiOperation(value = "查询所有用户信息")
    public R list(){
      return   workListService.selectAll();
    }
​
    @GetMapping("selectById")
    @ApiOperation(value = "查询单个用户信息")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id" ,value = "员工编号",required = true,dataType ="int")
    )
    public R selectById(Integer id){
        return workListService.selectByid(id);
    }
​
    @PostMapping ("/insert")
    @ApiOperation(value = "添加用户信息")
    public R insert(@RequestBody Workerlist workerlist){
        return workListService.insert(workerlist);
    }
​
    @PutMapping("/update")
    @ApiOperation(value = "修改用户信息")
    public R update(@RequestBody Workerlist workerlist){
        return workListService.update(workerlist);
    }
​
    @ApiOperation(value = "删除员工信息")
    @DeleteMapping("/delete")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id" ,value = "员工编号",required = true,dataType ="int")
    )
    public R delete(Integer id){
        return workListService.delete(id);
    }
}
​
  • 30
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值