1. 程式人生 > >SpringBoot 入門教程:整合mybatis,redis

SpringBoot 入門教程:整合mybatis,redis

SrpingBoot相較於傳統的專案具有配置簡單,能快速進行開發的特點,花更少的時間在各類配置檔案上,更多時間在具體業務邏輯上。

SPringBoot採用純註解方式進行配置,不喜歡xml配置的同學得仔細看了。

首先需要構建SpringBoot專案,除了傳統的自己構建好修改pom中依賴外,spring提供了更便捷的專案建立方式

勾選自己需要用到的東西,這裡我們構建標準的web專案,同時裡面使用到了mybatis,mysql,redis為例項進行建立,根據專案需要自己勾選相關專案,生成專案後並匯入到Eclipse等開發工具中,

注意:打包方式有jar和war, 如果要部署在tomcat中,建議選擇war

匯入後的專案已經是標準的web專案,直接通過tomcat部署訪問或者執行application.java的main方法,啟動後訪問一切正常。

增加資料庫訪問和mybatis相關操作配置:

1.首先在application.properties中增加資料來源配置

#datasource configuration
spring.datasource.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior
=convertToNull spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.max-active=10 spring.datasource.max-idle=5 spring.datasource.min-idle=0

2.修改Application.java,設定mapper介面掃描路徑和mybatis對應的xml路徑,還可以設定別名的包路徑等

已經資料來源,事物等

以前這些都需要自己在xml裡面配置,現在直接程式碼操作就好了,極大的減少了

修改後的程式碼如下: 注意紅色框內內容,根據需要酌情修改

3.定義操作資料庫的mapper,這裡需要注意的是,mapper上面不再需要@Repository這樣的註解標籤了

package com.xiaochangwei.mapper;

import java.util.List;

import com.xiaochangwei.entity.User;
import com.xiaochangwei.vo.UserParamVo;

/**
 * @since 2017年2月7日 下午1:58:46
 * @author 肖昌偉 [email protected]
 * @description
 */
public interface UserMapper {
    public int dataCount(String tableName);

    public List<User> getUsers(UserParamVo param);
}

4.定義放在對應目錄下的mapper.xml檔案

5.由於同時使用了redis,在application.properties中也加入redis相關配置

#redis configuration
#redis資料庫名稱  從0到15,預設為db0
spring.redis.database=1
#redis伺服器名稱
spring.redis.host=127.0.0.1
#redis伺服器密碼
spring.redis.password=
#redis伺服器連線埠號
spring.redis.port=6379
#redis連線池設定
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
#spring.redis.sentinel.master=
#spring.redis.sentinel.nodes=
spring.redis.timeout=60000

6,最後寫Controller程式碼,由於僅僅是測試,就沒有什麼規範可言了,直接調dao,方式和以前一樣,這裡沒啥變更

package com.xiaochangwei.controller;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.xiaochangwei.entity.User;
import com.xiaochangwei.mapper.UserMapper;
import com.xiaochangwei.vo.UserParamVo;

/**
 * @since 2017年2月7日 下午2:06:11
 * @author 肖昌偉 [email protected]
 * @description
 */

@RestController
public class UserController {

    protected static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserMapper userDao;

    @RequestMapping("/count/{tableName}")
    public int dataCount(@PathVariable String tableName) {
        return userDao.dataCount(tableName);
    }

    @RequestMapping(value = "/users", method = { RequestMethod.GET })
    public List<User> users(UserParamVo param) {
        return userDao.getUsers(param);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "stringRedisTemplate")
    ValueOperations<String, String> valueOperationStr;

    @RequestMapping("/redis/string/set")
    public String setKeyAndValue(String key, String value) {
        logger.debug("訪問set:key={},value={}", key, value);
        valueOperationStr.set(key, value);
        return "Set Ok";
    }

    @RequestMapping("/redis/string/get")
    public String getKey(String key) {
        logger.debug("訪問get:key={}", key);
        return valueOperationStr.get(key);
    }

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Resource(name = "redisTemplate")
    ValueOperations<Object, Object> valOps;

    @RequestMapping("/redis/obj/set")
    public void save(User user) {
        valOps.set(user.getId(), user);
    }

    @RequestMapping("/redis/obj/get")
    public User getPerson(String id) {
        return (User) valOps.get(id);
    }
}

至此,程式碼就編寫完了,啟動專案後訪問測試

1.查詢全部使用者資訊(無引數時)

2.根據引數查詢

3.redis設值

4.redis取值

至此,springboot中使用mybatis操作mysql資料庫和操作redis全部完成,需要原始碼的同學可以發郵件到的郵箱,我會盡快傳送給你

本文僅做簡易的學習測試,更多內容敬請期待後續相關文章

下一篇將講解springCloud入門

相關推薦

SpringBoot 入門教程整合mybatisredis

SrpingBoot相較於傳統的專案具有配置簡單,能快速進行開發的特點,花更少的時間在各類配置檔案上,更多時間在具體業務邏輯上。 SPringBoot採用純註解方式進行配置,不喜歡xml配置的同學得仔細看了。 首先需要構建SpringBoot專案,除了傳統的自己構建好修改

SpringBoot學習整合Mybatis使用HikariCP超高性能數據源

sta 掃描 sap url compile ack 項目結構 連接 style 一、添加pom依賴jar包: 1 <!--整合mybatis--> 2 <dependency> 3 <groupId>org.mybat

SpringBoot學習整合MyBatis使用Druid連線池

專案下載地址:http://download.csdn.NET/detail/aqsunkai/9805821 (一)新增pom依賴: <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/m

2.SpringBoot入門教程整合slf4j日誌配置

SpringBoot入門教程之整合slf4j日誌配置 Java日誌框架眾多,常用的有java.util.logging, log4j, logback,commons-logging等等。個人比較偏好的是slf4j,同時也比較偏好使用字尾為.propertie

SpringBoot入門系列第四篇 redis

一,準備工作,建立spring-boot-sample-redis工程 1、http://start.spring.io/      A、Artifact中輸入spring-boot-sample-redis      B、勾選Web下的web      C、勾選NOSQL

springboot整合mybatismysql做資料庫儲存redis做快取

redis應用的場景通過快取來減少對關係型資料庫的查詢次數,減輕資料庫壓力。在執行DAO類的select***(), query***()方法時,先從Redis中查詢有沒有快取資料,如果有則直接從Redis拿到結果,如果沒有再向資料庫發起查詢請求取資料。springboot已

springboot-整合mybatis-mysql-redis-quartzredis整合時就報錯

 .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  )

第三節SpringBoot整合shrioRedis快取session與許可權

1.建立Springboot專案 省略。。。 pom檔案 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="htt

SpringBoot整合mybatisSpringBoot中的junit測試

1、pom檔案中引入mybatis依賴:mybatis-spring-boot-starter 和mysql驅動依賴:mysql-connector-java,以及spring-boot-starter-test依賴用於junit測試        

springboot 2.0 教程-05-整合mybatis

閱讀原文:https://blog.bywind.cn/articles/2018/11/28/1543373589258.html 視訊教程:https://www.bilibili.com/video/av35595465 課程原始碼:https://github.com/ibywind/s

Spring Boot 基礎系列教程 | 第十六篇整合MyBatis

推薦 Spring Boot/Cloud 視訊: 最近專案原因可能會繼續開始使用MyBatis,已經習慣於spring-data的風格,再回頭看xml的對映配置總覺得不是特別舒服,介面定義與對映離散在不同檔案中,使得閱讀起來並不是特別方便。 Spring中整合

微服務 SpringBoot 2.0(九)整合Mybatis

我是SQL小白,我選Mybatis —— Java面試必修 引言 在第五章我們已經整合了Thymeleaf頁面框架,第七章也整合了JdbcTemplate,那今天我們再結合資料庫整合Mybatis框架 在接下來的文章中,我會用一個開源的部落格原始碼來做講解

springboot整合MyBatisUnsatisfied dependency expressed through field 'payParamMapper'

最近在做專案時候,使用springboot+mybatais時候,遇到下面這個問題,一時大意,記錄下異常資訊和解決方式 org.springframework.beans.factory.UnsatisfiedDependencyException: Erro

springboot 整合mybatismapper介面和對應的mapper對映檔案放在同一個包下的配置

一、springboot整合mybatis後,需要進行幾個步驟的配置: 1、mapper包下的mapper介面都需要新增@Mapper註解。 2、啟動類上面新增@MapperScan(basepackages={"com.web.mapper"})註解。 3、需要在po

SpringBoot 2.x(三)整合Mybatis的四種方式

前言 目前的大環境下,使用Mybatis作為持久層框架還是佔了絕大多數的,下面我們來說一下使用Mybatis的幾種姿勢。 姿勢一:零配置註解開發 第一步:引入依賴 首先,我們需要在pom檔案中新增依賴: 第二步:配置檔案 這裡我們採用yml來進行編寫,與properties檔案相比,yml看

SpringBoot 2.x(五)整合Mybatis-Plus

簡介 Mybatis-Plus是在Mybatis的基礎上,國人開發的一款持久層框架。 並且榮獲了2018年度開源中國最受歡迎的中國軟體TOP5 同樣以簡化開發為宗旨的Spring Boot與Mybatis-Plus放在一起會產生什麼樣的化學反應呢?下面我們來領略一下兩者配合帶來的效率上的提升。 Myba

springboot微服務搭建(一)整合mybatis配置(第一種方式)

現在看網上springboot整合mybatis有兩種方式:第一種是使用maven的mybatis的依賴,填寫配置檔案;第二種是採用spring-mybatis的配置。 第一種,在已有的springboot專案的pom檔案中加入 <dependency>

React Native基礎&入門教程以一個To Do List小例子看props和state

本文由葡萄城技術團隊於部落格園原創並首發 轉載請註明出處:葡萄城官網,葡萄城為開發者提供專業的開發工具、解決方案和服務,賦能開發者。 在上篇中,我們介紹了什麼是Flexbox佈局,以及如何使用Flexbox佈局。還沒有看過的小夥伴歡迎回到文章列表點選檢視之前的文章瞭解。 那麼,當我們有了基本

一起來學 SpringBoot 2.x | 第七篇整合 Mybatis

點選上方“芋道原始碼”,選擇“置頂公眾號”技術文章第一時間送達!原始碼精品專欄 摘要: 原創出處

使用SpringBoot搭建小型專案,整合mybatis,redis,swagger2,並部署在外部容器中。

一  簡介  初次接觸springboot,最直觀的感受是搭建專案幾乎不需要任何配置檔案,自帶Tomcat容器,節省了很多開發和部署時間,專案也變得更加精簡。  SpringBoot主要特性:  1 spring Boot Starter:它將常用的依賴分組進行了整合,將其合