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 肖昌偉 317409898@qq.com
 * @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 肖昌偉 317409898@qq.com
 * @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全部完成,需要源碼的同學可以發郵件到的郵箱,我會盡快發送給你

代碼現已托管到: http://git.oschina.net/xiaochangwei/spring-boot ,請需要的同學下載使用

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

 

下一篇將講解springCloud入門

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM