SpringBoot技术

时间:2021-08-16 22:58:10   收藏:0   阅读:21

1. SpringBoot数据访问

1.1  Spring Boot整合MyBatis

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

# 开启驼峰命名匹配映射
mybatis:
  configuration:
    map-underscore-to-camel-case: true

1.2 Spring Boot整合Redis

<!-- redis依赖包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
#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
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视图技术

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 用于指定标签显示的文本内容

 

3. SpringBoot实战演练

技术分享图片

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency>
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();
    }
}

 

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>
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();
    }
}
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";
    }



}
##服务器配置
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);
    }

}

技术分享图片

 

4. SpringBoot部署

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();
    }
}

原文:https://www.cnblogs.com/forever-fate/p/15150124.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!