zoukankan      html  css  js  c++  java
  • 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入门

  • 相关阅读:
    第k小元素学习记录
    线段树学习笔记
    数论方面的知识积累
    javascript 例子
    数据绑定以及Container.DataItem的具体分析
    C#委托和事件
    C#中的特性(Attributes)(翻译)
    gridview和repeater中取得行的序号
    理解 Ajax 及其工作原理,构建网站的一种有效方法
    JS数组对象参考
  • 原文地址:https://www.cnblogs.com/xiaochangwei/p/6374514.html
Copyright © 2011-2022 走看看