Java教程

SpringBoot技术

本文主要是介绍SpringBoot技术,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. SpringBoot数据访问

1.1  Spring Boot整合MyBatis

MyBatis 是一款优秀的持久层框架,Spring Boot官方虽然没有对MyBatis进行整合,但是MyBatis团队自行适配了对应的启动器,进一步简化了使用MyBatis进行数据的操作

  • 基础环境搭建
    • 数据准备:在MySQL中,先创建了一个数据库springbootdata,然后创建了两个表t_article和t_comment并向表中插入数据。其中评论表t_comment的a_id与文章表t_article的主键id相关联
    # 创建数据库
    CREATE DATABASE springbootdata;
    # 选择使用数据库
    USE springbootdata;
    # 创建表t_article并插入相关数据
    DROP TABLE IF EXISTS t_article;
    CREATE TABLE t_article (
    id int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
    title varchar(200) DEFAULT NULL COMMENT '文章标题',
    content longtext COMMENT '文章内容',
    PRIMARY KEY (id)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    INSERT INTO t_article VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
    INSERT INTO t_article VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
    # 创建表t_comment并插入相关数据
    DROP TABLE IF EXISTS t_comment;
    CREATE TABLE t_comment (
    id int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',
    content longtext COMMENT '评论内容',
    author varchar(200) DEFAULT NULL COMMENT '评论作者',
    a_id int(20) DEFAULT NULL COMMENT '关联的文章id',
    PRIMARY KEY (id)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    INSERT INTO t_comment VALUES ('1', '很全、很详细', 'lucy', '1');
    INSERT INTO t_comment VALUES ('2', '赞一个', 'tom', '1');
    INSERT INTO t_comment VALUES ('3', '很详细', 'eric', '1');
    INSERT INTO t_comment VALUES ('4', '很好,非常详细', '张三', '1');
    INSERT INTO t_comment VALUES ('5', '很不错', '李四', '2');
    • 创建项目,引入相应的启动器
    • 编写与数据库表t_comment和t_article对应的实体类Comment和Article
    package com.rf.entity;
    
    import lombok.Data;
    
    @Data
    public class Comment {
        private Integer id;
        private String content;
        private String author;
        private Integer aId;
    }
    
    package com.rf.entity;
    
    import lombok.Data;
    
    @Data
    public class Article {
        private Integer id;
        private String title;
        private String content;
    
    }
    • 编写配置文件:在application.yml配置文件中进行数据库连接配置
    #MySQL数据库连接配置
    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        username: root
        url: jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC&characterEncoding=UTF-8
        password: 123456
  • 注解方式整合Mybatis实现需求:通过ID查询Comment信息
    • 创建一个对t_comment表数据操作的接口CommentMapper
    package com.rf.mapper;
    
    import com.rf.entity.Comment;
    import org.apache.ibatis.annotations.Select;
    @Component
    public interface CommentMapper {
        /**
         * 通过ID查询Comment信息
         * @param id
         * @return
         */
        @Select("select * from t_comment where id=#{id}")
        public Comment findById(Integer id);
    }
    • 在Spring Boot项目启动类上添加@MapperScan("xxx")注解
    package com.rf;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @MapperScan("com.rf.mapper")
    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }
    • 编写测试方法
    package com.rf.demo;
    
    import com.rf.entity.Comment;
    import com.rf.mapper.CommentMapper;
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    class DemoApplicationTests {
    
        @Test
        void contextLoads() {
        }
    
        @Autowired
        private CommentMapper commentMapper;
        @Test
        public void commentTest(){
            Comment comment = commentMapper.findById(1);
            System.out.println("comment = " + comment);
        }
    
    }
  • 为了解决驼峰命名方式造成的表字段值无法正确映射到类属性的情况,可以在Spring Boot全局配置文件application.properties中添加开启驼峰命名匹配映射配置
# 开启驼峰命名匹配映射
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  • 配置文件的方式整合MyBatis
    • 使用Free Mybatis plugin插件生成 :创建一个用于对数据库表t_article数据操作的接口ArticleMapper,创建XML映射文件resources目录下创建一个统一管理映射文件的包mapper,并在该包下编写与ArticleMapper接口方应的映射文件ArticleMapper.xml
    package com.rf.entity;
    
    import java.io.Serializable;
    import lombok.Data;
    
    /**
     * t_article
     * @author 
     */
    @Data
    public class TArticle implements Serializable {
        /**
         * 文章id
         */
        private Integer id;
    
        /**
         * 文章标题
         */
        private String title;
    
        /**
         * 文章内容
         */
        private String content;
    
        private static final long serialVersionUID = 1L;
    
        @Override
        public boolean equals(Object that) {
            if (this == that) {
                return true;
            }
            if (that == null) {
                return false;
            }
            if (getClass() != that.getClass()) {
                return false;
            }
            TArticle other = (TArticle) that;
            return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
                && (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))
                && (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent()));
        }
    
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
            result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode());
            result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode());
            return result;
        }
    
        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append(getClass().getSimpleName());
            sb.append(" [");
            sb.append("Hash = ").append(hashCode());
            sb.append(", id=").append(id);
            sb.append(", title=").append(title);
            sb.append(", content=").append(content);
            sb.append(", serialVersionUID=").append(serialVersionUID);
            sb.append("]");
            return sb.toString();
        }
    }
    
    
    
    package com.rf.mapper;
    
    import com.rf.entity.TArticle;
    @Component
    public interface TArticleMapper {
        int deleteByPrimaryKey(Integer id);
    
        int insert(TArticle record);
    
        int insertSelective(TArticle record);
    
        TArticle selectByPrimaryKey(Integer id);
    
        int updateByPrimaryKeySelective(TArticle record);
    
        int updateByPrimaryKey(TArticle record);
    }
    <?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.rf.mapper.TArticleMapper">
      <resultMap id="BaseResultMap" type="com.rf.entity.TArticle">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="title" jdbcType="VARCHAR" property="title" />
        <result column="content" jdbcType="VARCHAR" property="content" />
      </resultMap>
      <sql id="Base_Column_List">
        id, title, content
      </sql>
      <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select 
        <include refid="Base_Column_List" />
        from t_article
        where id = #{id,jdbcType=INTEGER}
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from t_article
        where id = #{id,jdbcType=INTEGER}
      </delete>
      <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.rf.entity.TArticle" useGeneratedKeys="true">
        insert into t_article (title, content)
        values (#{title,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR})
      </insert>
      <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.rf.entity.TArticle" useGeneratedKeys="true">
        insert into t_article
        <trim prefix="(" suffix=")" suffixOverrides=",">
          <if test="title != null">
            title,
          </if>
          <if test="content != null">
            content,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
          <if test="title != null">
            #{title,jdbcType=VARCHAR},
          </if>
          <if test="content != null">
            #{content,jdbcType=VARCHAR},
          </if>
        </trim>
      </insert>
      <update id="updateByPrimaryKeySelective" parameterType="com.rf.entity.TArticle">
        update t_article
        <set>
          <if test="title != null">
            title = #{title,jdbcType=VARCHAR},
          </if>
          <if test="content != null">
            content = #{content,jdbcType=VARCHAR},
          </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.rf.entity.TArticle">
        update t_article
        set title = #{title,jdbcType=VARCHAR},
          content = #{content,jdbcType=VARCHAR}
        where id = #{id,jdbcType=INTEGER}
      </update>
    </mapper>
    • 配置XML映射文件路径:在项目中编写的XML映射文件,Spring Boot并无从知晓,所以无法扫描到该自定义编写的XML配置文件,还必须在全局配置文件application.properties中添加MyBatis映射文件路径的配置,同时需要添加实体类别名映射路径
    # 开启驼峰命名匹配映射
    mybatis:
      configuration:
        map-underscore-to-camel-case: true
    #配置MyBatis的xml配置文件路径
      mapper-locations: classpath:mapper/*.xml
      #配置XML映射文件中指定的实体类别名路径
      type-aliases-package: com.rf.entity
    • 编写单元测试进行接口方法测试
          @Autowired
          private TArticleMapper articleMapper;
          @Test
          public void articleTest(){
              TArticle article = articleMapper.selectByPrimaryKey(1);
              System.out.println("article = " + article);
          }
      

       

       

1.2 Spring Boot整合Redis

  • 添加Redis依赖包在项目的pom.xml中添加
<!-- redis依赖包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  • 配置Redis数据库连接:在application.properties中配置redis数据库连接信息
#redis配置
#Redis服务器地址
spring.redis.host=192.168.80.128
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database=0
#连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=50
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=3000
#连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=20
#连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=2
#连接超时时间(毫秒)
spring.redis.timeout=5000 
  • 编写Redis操作工具类:将RedisTemplate实例包装成一个工具类,便于对redis进行数据操作
package com.rf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.security.DenyAll;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 读取缓存
     * *
     @param key
      * @return
     */
    public Object get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }
    /**
      * 写入缓存
    */
    public boolean set( String key, Object value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value,1, TimeUnit.DAYS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 更新缓存
     */
    public boolean getAndSet(final String key, String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            result = true;
        } catch (Exception e) {e.printStackTrace();
        }
        return result;
    }
    /**
    * 删除缓存
     */
    public boolean delete(final String key) {
        boolean result = false;
        try {
            redisTemplate.delete(key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
  • 测试
package com.rf.demo;

import com.rf.config.RedisUtils;
import com.rf.entity.Comment;
import com.rf.entity.TArticle;
import com.rf.mapper.CommentMapper;
import com.rf.mapper.TArticleMapper;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
class DemoApplicationTests {

   
    @Autowired
    private TArticleMapper articleMapper;


    @Autowired
    private RedisUtils redisUtils;
    @Test
    public void setRedisData() {
        redisUtils.set("article_1",articleMapper.selectByPrimaryKey(1));
        System.out.println("success");
    }
    @Test
    public void getRedisData() {
        TArticle article = (TArticle) redisUtils.get("article_1");
        System.out.println(article);
    }
}

2. SpringBoot视图技术

  • Spring Boot框架对很多常用的模板引擎技术(如:FreeMarker、Thymeleaf、Mustache等)提供了整合支持
  • Spring Boot不太支持常用的JSP模板,并且没有提供对应的整合配置,这是因为使用嵌入式Servlet容器的Spring Boot应用程序对于JSP模板存在一些限制
    • 在Jetty和Tomcat容器中,Spring Boot应用被打包成war文件可以支持JSP。但Spring Boot默认使用嵌入式Servlet容器以JAR包方式进行项目打包部署,这种JAR包方式不支持JSP
    • 如果使用Undertow嵌入式容器部署Spring Boot项目,也不支持JSP模板
    • Spring Boot默认提供了一个处理请求路径“/error”的统一错误处理器,返回具体的异常信息。使用JSP模板时,无法对默认的错误处理器进行覆盖,只能根据Spring Boot要求在指定位置定制错误页面。

2.1 Thymeleaf

  Thymeleaf是一种现代的基于服务器端的Java模板引擎技术,也是一个优秀的面向Java的XML、XHTML、HTML5页面模板,它具有丰富的标签语言、函数和表达式,在使用Spring Boot框架进行页面
设计时,一般会选择Thymeleaf模板

  • 常用标签
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="all"
href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
<title>Title</title>
</head>
<body>
<p th:text="${hello}">欢迎进入Thymeleaf的学习</p>
</body>
</html>

  在HTML页面上使用Thymeleaf标签,Thymeleaf 标签能够动态地替换掉静态内容,使页面动态展示。上述代码中,“xmlns:th="http://www.thymeleaf.org"“ 用于引入Thymeleaf模板引擎标签,使用关键字“th”标注标签是Thymeleaf模板提供的标签,其中,“th:href”用于引入外联样式文件,“th:text”用于动态显示标签文本内容。除此之外,Thymeleaf模板提供了很多标签

th:标签 说明
th:insert 布局标签,替换内容到引入的文件
th:replace 页面片段包含(类似JSP中的include标签)
th:each 元素遍历(类似JSP中的c:forEach标签)
th:if 条件判断,如果为真
th:unless 条件判断,如果为假
th:switch 条件判断,进行选择性匹配
th:case 条件判断,进行选择性匹配
th:value 属性值修改,指定标签属性值
th:href 用于设定链接地址
th:src 用于设定链接地址
th:text 用于指定标签显示的文本内容

 

  • 标准表达式:
    • 变量表达式 ${...}:用于获取上下文中的变量值
    <p th:text="${title}">这是标题</p> 
    
    <!-- 如果当前程序没有启动或者当前上下文中不存在title变量,该片段会显示标签默认值“这是标题”;
    如果当前上下文中存在title变量并且程序已经启动,当前P标签中的默认文本内容将会被title变量的值所替换,从而达到模板引擎页面数据动态替换的效果 -->
    Thymeleaf为变量所在域提供了一些内置对象 
    # ctx:上下文对象
    # vars:上下文变量
    # locale:上下文区域设置
    # request:(仅限Web Context)HttpServletRequest对象
    # response:(仅限Web Context)HttpServletResponse对象
    # session:(仅限Web Context)HttpSession对象
    # servletContext:(仅限Web Context)ServletContext对象
    The locale country is: <span th:text="${#locale.country}">US</span>
    <!-- 使用th:text="${#locale.country}"动态获取当前用户所在国家信息,其中标签内默认内容为US(美国),
    程序启动后通过浏览器查看当前页面时,Thymeleaf会通过浏览器语言设置来识别当前用户所在国家信息,从而实现动态替换-->
    • 选择变量表达式 *{...}:一般用于从被选定对象而不是上下文中获取属性值,如果没有选定对象,则和变量表达式一样
    <div th:object="${book}">
    <p>titile: <span th:text="*{title}">标题</span>.</p>
    </div>
    
    <!--  *{title} 选择变量表达式获取当前指定对象book的title属性值 -->
    • 消息表达式#{...}:用于Thymeleaf模板页面国际化内容的动态替换和展示,需要提供一些国际化配置文件
    • 链接URL表达式 @{...}:用于页面跳转或者资源的引入,在Web开发中占据着非常重要的地位
    <a th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">view</a>
    <a th:href="@{/order/details(orderId=${o.id},pid=${p.id})}">view</a>
    
    <!-- 链接表达式@{...}分别编写了绝对链接地址和相对链接地址。
    在有参表达式中,需要按照@{路径(参数名称=参数值,参数名称=参数值...)}的形式编写,\同时该参数的值可以使用变量表达式来传递动态参数值-->
    • 片段表达式 ~{...}
    <div th:insert="~{thymeleafDemo::title}"></div>
    <!-- 使用th:insert属性将title片段模板引用到该标签中。
    thymeleafDemo为模板名称,Thymeleaf会自动查找“/resources/templates/”目录下的thymeleafDemo模板,title为片段名称-->
  • 基本使用
    • Thymeleaf模板基本配置
    <!-- 引入Thymeleaf依赖-->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    在全局配置文件中配置Thymeleaf模板的一些参数。一般Web项目都会使用下列配置

    spring.thymeleaf.cache = true #启用模板缓存
    spring.thymeleaf.encoding = UTF-8 #模板编码
    spring.thymeleaf.mode = HTML5 #应用于模板的模板模式
    spring.thymeleaf.prefix = classpath:/templates/ #指定模板页面存放路径
    spring.thymeleaf.suffix = .html #指定模板页面名称的后缀


    上述配置中,spring.thymeleaf.cache表示是否开启Thymeleaf模板缓存,默认为true,在开发过程中通常会关闭缓存,保证项目调试过程中数据能够及时响应;

    spring.thymeleaf.prefix指定了Thymeleaf模板页面的存放路径,默认为classpath:/templates/;

    spring.thymeleaf.suffix指定了Thymeleaf模板页面的名称后缀,默认为.html

    • 静态资源的访问
      • Spring boot默认设置了静态资源的访问路径
      • 使用Spring Initializr方式创建的Spring Boot项目,默认生成了一个resources目录,在resources目录中新建public、resources、static三个子目录下,Spring boot默认会挨个从public、resources、static里面查找静态资源
    • 完成数据的页面展示
      •  创建Spring Boot项目,引入Thymeleaf依赖 
      •  编写配置文件
      #启用模板缓存
      spring.thymeleaf.cache = true 
      •  创建web控制类:在项目中创建名为com.rf.controller的包,并在该包下创建一个用于前端模板页面动态数据替换效果测试的访问实体类LoginController toLoginPage()方法用于向登录页面login.html跳转,同时携带了当前年份信息currentYear。
      package com.rf.controller;
      
      import org.springframework.stereotype.Controller;
      import org.springframework.ui.Model;
      import org.springframework.web.bind.annotation.RequestMapping;
      
      import java.util.Calendar;
      
      @Controller
      public class LoginController {
          @RequestMapping("/toLoginPage")
          public String toLoginPage(Model model){
              model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
              return "login";
          }
      
      }
      • 创建模板页面并引入静态资源文件,在“classpath:/templates/”目录下引入一个用户登录的模板页面login.html ;通过“xmlns:th="http://www.thymeleaf.org"”引入了Thymeleaf模板标签;使用“th:href”和“th:src”分别引入了两个外联的样式文件和一个图片;使用“th:text”引入了后台动态传递过来的当前年份currentYear
      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1,shrinkto-fit=no">
          <title>用户登录界面</title>
          <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
          <link th:href="@{/login/css/signin.css}" rel="stylesheet">
      </head>
      <body class="text-center">
      <!-- 用户登录form表单 -->
      <form class="form-signin">
          <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
          <h1 class="h3 mb-3 font-weight-normal">请登录</h1>
          <input type="text" class="form-control"
                 th:placeholder="用户名" required="" autofocus="">
          <input type="password" class="form-control"
                 th:placeholder="密码" required="">
          <div class="checkbox mb-3">
              <label>
                  <input type="checkbox" value="remember-me"> 记住我
              </label>
          </div>
          <button class="btn btn-lg btn-primary btn-block" type="submit" >登录</button>
          <p class="mt-5 mb-3 text-muted">© <span
                  th:text="${currentYear}">2019</span>-<span
                  th:text="${currentYear}+1">2020</span></p>
      </form>
      </body>
      </html>
      • 效果测试 :登录页面login.html显示正常,在文件4-3中使用“th:*”相关属性引入的静态文件生效,并且在页面底部动态显示了当前日期2021-2022,而不是文件中的静态数字2019-2020。这进一步说明了Spring Boot与Thymeleaf整合成功,完成了静态资源的引入和动态数据的显示

3. SpringBoot实战演练

  • 创建springboot工程

  • 导入pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency>
  • User实体类编写
package com.rf.entity;

import java.io.Serializable;
import lombok.Data;

/**
 * users
 * @author 
 */
@Data
public class Users implements Serializable {
    private Integer uid;

    private String username;

    private String password;

    private String phone;

    private String createtime;

    private static final long serialVersionUID = 1L;

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        Users other = (Users) that;
        return (this.getUid() == null ? other.getUid() == null : this.getUid().equals(other.getUid()))
            && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername()))
            && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword()))
            && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone()))
            && (this.getCreatetime() == null ? other.getCreatetime() == null : this.getCreatetime().equals(other.getCreatetime()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getUid() == null) ? 0 : getUid().hashCode());
        result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode());
        result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode());
        result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode());
        result = prime * result + ((getCreatetime() == null) ? 0 : getCreatetime().hashCode());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", uid=").append(uid);
        sb.append(", username=").append(username);
        sb.append(", password=").append(password);
        sb.append(", phone=").append(phone);
        sb.append(", createtime=").append(createtime);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

 

  • UserMapper编写及Mapper文件
package com.rf.mapper;

import com.rf.entity.Users;

import java.util.List;

public interface UsersDao {
    /**
     * 按ID删除
     * @param uid
     * @return
     */
    int deleteByPrimaryKey(Integer uid);

    /**
     * 新增
     * @param record
     * @return
     */
    int insert(Users record);
    /**
     * 判断是否为空的新增
     * @param record
     * @return
     */
    int insertSelective(Users record);

    /**
     * g根据ID查询
     * @param uid
     * @return
     */
    Users selectByPrimaryKey(Integer uid);

    /**
     * 判断是否为空的修改
     * @param record
     * @return
     */
    int updateByPrimaryKeySelective(Users record);

    /**
     * 修改
     * @param record
     * @return
     */
    int updateByPrimaryKey(Users record);

    /**
     * 查询所有
     * @return
     */
    List<Users> queryAll();
}
<?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.rf.mapper.UsersDao">
  <resultMap id="BaseResultMap" type="com.rf.entity.Users">
    <id column="uid" jdbcType="INTEGER" property="uid" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="PASSWORD" jdbcType="VARCHAR" property="password" />
    <result column="phone" jdbcType="VARCHAR" property="phone" />
    <result column="createtime" jdbcType="VARCHAR" property="createtime" />
  </resultMap>
  <sql id="Base_Column_List">
    `uid`, username, `PASSWORD`, phone, createtime
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from users
    where `uid` = #{uid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from users
    where `uid` = #{uid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" keyColumn="uid" keyProperty="uid" parameterType="com.rf.entity.Users" useGeneratedKeys="true">
    insert into users (username, `PASSWORD`, phone, 
      createtime)
    values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, 
      #{createtime,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" keyColumn="uid" keyProperty="uid" parameterType="com.rf.entity.Users" useGeneratedKeys="true">
    insert into users
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="username != null">
        username,
      </if>
      <if test="password != null">
        `PASSWORD`,
      </if>
      <if test="phone != null">
        phone,
      </if>
      <if test="createtime != null">
        createtime,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="phone != null">
        #{phone,jdbcType=VARCHAR},
      </if>
      <if test="createtime != null">
        #{createtime,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.rf.entity.Users">
    update users
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        `PASSWORD` = #{password,jdbcType=VARCHAR},
      </if>
      <if test="phone != null">
        phone = #{phone,jdbcType=VARCHAR},
      </if>
      <if test="createtime != null">
        createtime = #{createtime,jdbcType=VARCHAR},
      </if>
    </set>
    where `uid` = #{uid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.rf.entity.Users">
    update users
    set username = #{username,jdbcType=VARCHAR},
      `PASSWORD` = #{password,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=VARCHAR},
      createtime = #{createtime,jdbcType=VARCHAR}
    where `uid` = #{uid,jdbcType=INTEGER}
  </update>

  <select id="queryAll" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from users
  </select>
</mapper>
  • UserService接口及实现类编写
package com.rf.service;

import com.rf.entity.Users;

import java.util.List;

/**
 * (Users)表服务接口
 *
 * @author rf
 * @since 2021-08-16 21:00:31
 */
public interface UsersService {

    /**
     * 按ID删除
     * @param uid
     * @return
     */
    void deleteByPrimaryKey(Integer uid);

    /**
     * 新增
     * @param record
     * @return
     */
    void insert(Users record);
    /**
     * 判断是否为空的新增
     * @param record
     * @return
     */
    void insertSelective(Users record);

    /**
     * g根据ID查询
     * @param uid
     * @return
     */
    Users selectByPrimaryKey(Integer uid);

    /**
     * 判断是否为空的修改
     * @param record
     * @return
     */
    void updateByPrimaryKeySelective(Users record);

    /**
     * 修改
     * @param record
     * @return
     */
    void updateByPrimaryKey(Users record);
    /**
     * 查询所有
     * @return
     */
    List<Users> queryAll();

}
package com.rf.service.impl;

import com.rf.entity.Users;
import com.rf.mapper.UsersDao;
import com.rf.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * (Users)表服务实现类
 *
 * @author rf
 * @since 2021-08-16 21:00:31
 */
@Service("usersService")
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersDao usersDao;


    @Override
    public void deleteByPrimaryKey(Integer uid) {
        usersDao.deleteByPrimaryKey(uid);
    }

    @Override
    public void insert(Users record) {
usersDao.insert(record);
    }

    @Override
    public void insertSelective(Users record) {
usersDao.insertSelective(record);
    }

    @Override
    public Users selectByPrimaryKey(Integer uid) {
        return usersDao.selectByPrimaryKey(uid);
    }

    @Override
    public void updateByPrimaryKeySelective(Users record) {
usersDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public void updateByPrimaryKey(Users record) {
usersDao.updateByPrimaryKey(record);
    }

    @Override
    public List<Users> queryAll() {
        return usersDao.queryAll();
    }
}
  • UserController编写
package com.rf.controller;

import com.rf.entity.Users;
import com.rf.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * (Users)表控制层
 *
 * @author rf
 * @since 2021-08-16 21:00:32
 */
@RestController
public class UsersController {
    /**
     * 服务对象
     */
    @Autowired
    private UsersService usersService;


    @GetMapping("/user")
    public List<Users> queryAll(){
    return usersService.queryAll();
}
    @GetMapping("/user/{uid}")
    public Users selectByPrimaryKey(@PathVariable("uid") Integer uid){
        return usersService.selectByPrimaryKey(uid);
    }
    @PostMapping("/insert")
    public String insert(Users users){
        usersService.insertSelective(users);
        return "success";
    }
    @PutMapping("/update")
    public String update(Users users){
        usersService.updateByPrimaryKeySelective(users);
        return "success";
    }
    @DeleteMapping("/delete/{uid}")
    public String delete(@PathVariable("uid") Integer uid){
        usersService.deleteByPrimaryKey(uid);
        return "success";
    }



}
  • application.yml
##服务器配置
server:
  port: 8090
servlet:
    context-path: /

##数据源配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/smd?serverTimezone=UTC&characterEncoding=UTF-8
    username: root
    password: 123456
    name: druid
    type: com.alibaba.druid.pool.DruidDataSource
#整合mybatis
mybatis:
  #声明Mybatis映射文件所在的位置
mapper-locations: classpath:mapper/*.xml
  • 启动类   
package com.rf;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.rf.mapper")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
  • 使用Postman测试

 

4. SpringBoot部署

  • 配置文件中添加打包组件依赖
    <build>
    <plugins>
    <!-- 打jar包时如果不配置该插件,打出来的jar包没有清单文件 -->
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    </plugins>
    </build>
  • 使用maven package打包成jar包
  • 使用java -jar 项目.jar运行
package com.rf.entity;

import java.io.Serializable;
import lombok.Data;

/**
 * users
 * @author 
 */
@Data
public class Users implements Serializable {
    private Integer uid;

    private String username;

    private String password;

    private String phone;

    private String createtime;

    private static final long serialVersionUID = 1L;

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        Users other = (Users) that;
        return (this.getUid() == null ? other.getUid() == null : this.getUid().equals(other.getUid()))
            && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername()))
            && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword()))
            && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone()))
            && (this.getCreatetime() == null ? other.getCreatetime() == null : this.getCreatetime().equals(other.getCreatetime()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getUid() == null) ? 0 : getUid().hashCode());
        result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode());
        result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode());
        result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode());
        result = prime * result + ((getCreatetime() == null) ? 0 : getCreatetime().hashCode());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", uid=").append(uid);
        sb.append(", username=").append(username);
        sb.append(", password=").append(password);
        sb.append(", phone=").append(phone);
        sb.append(", createtime=").append(createtime);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}
这篇关于SpringBoot技术的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!