demon 目录,公共配置

SbMybatisApplication.java

package com.example.sb_mybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication
@MapperScan("com.example.sb_mybatis.mapper")
@ServletComponentScan
public class SbMybatisApplication { public static void main(String[] args) {
SpringApplication.run(SbMybatisApplication.class, args);
}
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId>
<artifactId>sb_mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>sb_mybatis</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

application.properties:

mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.example.sb_mybatis.entity
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
#Druid
spring.datasource.druid.initial-size=3
spring.datasource.druid.min-idle=3
spring.datasource.druid.max-active=10
spring.datasource.druid.max-wait=60000
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000
#Redis
# Redis 数据库索引(默认为0)
spring.redis.database=0
# Redis 服务器地址
spring.redis.host=127.0.0.1
# Redis 服务器连接端口
spring.redis.port=6379
# Redis 服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=10000

spring boot + mybatis

User.java

package com.example.sb_mybatis.entity;

import com.example.sb_mybatis.enums.UserSexEnum;
import lombok.Data; import java.io.Serializable; @Data
public class User implements Serializable {
private Long id;
private String userName;
private String passWord;
private UserSexEnum userSex;
private String nickName; public User(String userName, String passWord, UserSexEnum userSex, String nickName) {
this.userName = userName;
this.passWord = passWord;
this.userSex = userSex;
this.nickName = nickName;
} public User() {
}
}

UserSexEnum.java

package com.example.sb_mybatis.enums;

public enum UserSexEnum {
MAN, WOMAN
}

UserMapper.java

package com.example.sb_mybatis.mapper;

import com.example.sb_mybatis.entity.User;

import java.util.List;

public interface UserMapper {

    List<User> getAll();

    User getOne(Long id);

    void insert(User user);

    void update(User user);

    void delete(Long id);
}

userMapper.xml

<?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.example.sb_mybatis.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.sb_mybatis.entity.User">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="userName" property="userName" jdbcType="VARCHAR"/>
<result column="passWord" property="passWord" jdbcType="VARCHAR"/>
<result column="user_sex" property="userSex" javaType="com.example.sb_mybatis.enums.UserSexEnum"/>
<result column="nick_name" property="nickName" jdbcType="VARCHAR"/>
</resultMap> <sql id="Base_Column_List">
id, userName, passWord, user_sex, nick_name
</sql> <select id="getAll" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM users
</select> <select id="getOne" parameterType="Long" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM users where id = #{id}
</select> <insert id="insert" parameterType="User">
INSERT INTO users
(userName, passWord, user_sex, nick_name)
values (#{userName},#{passWord},#{userSex},#{nickName})
</insert> <update id="update" parameterType="User" >
UPDATE users SET
userName=#{userName},passWord=#{passWord},user_sex=#{userSex},nick_name=#{nickName}
</update> <delete id="delete" parameterType="Long" >
DELETE FROM users where id=#{id}
</delete>
</mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer"/>
<typeAlias alias="Long" type="java.lang.Long"/>
<typeAlias alias="HashMap" type="java.util.HashMap"/>
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/>
<typeAlias alias="ArrayList" type="java.util.ArrayList"/>
<typeAlias alias="LinkedList" type="java.util.LinkedList"/>
<typeAlias alias="User" type="com.example.sb_mybatis.entity.User"/>
</typeAliases> </configuration>

测试类,UserService就是直接调用mapper的发方法(代码略)

package com.example.sb_mybatis.service;

import com.example.sb_mybatis.entity.User;
import com.example.sb_mybatis.enums.UserSexEnum;
import org.junit.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; import static org.junit.Assert.*; @RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest { @Autowired
UserService service; @Test
public void getAll() {
System.out.println(service.getAll());
} @Test
public void getOne() {
System.out.println(service.getOne(123L));
} @Test
public void insert() {
User u = new User("aaa", "123456", UserSexEnum.MAN, "nickname");
service.insert(u);
} @Test
public void update() {
User u = service.getOne(123L);
u.setNickName("hello");
service.update(u);
} @Test
public void delete() {
service.delete(123L);
}
}

spring boot + redis

缓存

package com.example.sb_mybatis.conf;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate; import java.lang.reflect.Method; @Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport { @Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
} @Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
//rcm.setDefaultExpiration(60);//秒
return rcm;
}
}

RedisHttpSession

package com.example.sb_mybatis.conf;

import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)
public class SessionConfig {
}

测试类

package com.example.sb_mybatis.web;

import com.example.sb_mybatis.entity.User;
import com.example.sb_mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map; @RestController
public class RedisTest { @Autowired
UserService userService; @RequestMapping("/hello")
@Cacheable(value = "helloCache")
public String hello(String name) {
System.out.println("没有走缓存!");
return "hello " + name;
} @RequestMapping("/condition")
@Cacheable(value = "condition", condition = "#name.length() <= 4")
public String condition(String name) {
System.out.println("没有走缓存!");
return "hello " + name;
} @RequestMapping("/u_list")
@Cacheable(value = "usersCache", key = "#k")
public List<User> getUsers(String k) {
List<User> users = userService.getAll();
System.out.println("执行了数据库操作");
return users;
} @RequestMapping("/u_list_update")
@CachePut(value = "usersCache", key = "#k")
public List<User> getUsers_update(String k) {
List<User> users = userService.getAll();
System.out.println("执行了数据库操作");
return users;
} @RequestMapping("/u_list_del")
@CacheEvict(value = "usersCache", allEntries = true)
public List<User> getUsers_del() {
List<User> users = userService.getAll();
System.out.println("执行了数据库操作");
return users;
} @RequestMapping(value = "/setSession", method = RequestMethod.GET)
public Map<String, Object> setSession (HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
request.getSession().setAttribute("request_Url", request.getRequestURL());
request.getSession().setAttribute("message", request.getRequestURL());
map.put("request Url", request.getRequestURL());
return map;
} @RequestMapping(value = "/getSession")
public Object getSession (HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
map.put("sessionId", request.getSession().getId());
map.put("message", request.getSession().getAttribute("message"));
map.put("request_Url", request.getSession().getAttribute("request_Url"));
System.out.println("==getSession==");
return map;
} }

注意:

@Cacheable(value = "usersCache", key = "#k") 和@CachePut(value = "usersCache", key = "#k")需要指定一个相同的key,

访问时url后加上 ?k=123

如果不指定,@CachePut不能更新redis里@Cacheable对应的值,不知道是不是bug,有待进一步了解。

spring boot 笔记1的更多相关文章

  1. spring boot 笔记--第三章

    spring boot 笔记 第三章,使用Spring boot 构建系统: 强烈建议支持依赖管理的构建系统,Maven或Gradle 依赖管理: Spring Boot的每版本都会提供它支持的依赖列 ...

  2. Spring Boot笔记二:快速创建以及yml文件自动注入

    上个笔记写了如何自己去创建Spring boot,以及如何去打jar包,其实,还是有些麻烦的,我们还自己新建了几个文件夹不是. Idea可以让我们快速的去创建Spring boot应用,来看 一.快速 ...

  3. Spring Boot 笔记 (1) - Maven、基本配置、Profile的使用

    一. Spring Boot 简介 开箱即用的一站式 Java EE 解决方案 Spring 技术栈的大整合 核心问题 暂时无法回答 Spring Boot 和 SOA 有什么区别? Spring B ...

  4. Spring Boot笔记(一)

    Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过 ...

  5. Spring Boot笔记六:Thymeleaf介绍

    目录 什么是thymeleaf? 创建最简单的thymeleaf thymeleaf语法 什么是thymeleaf? thymeleaf是一个模板引擎,是用来在Spring Boot中代替JSP的 引 ...

  6. Spring Boot笔记五: Web开发之Webjar和静态资源映射规则

    目录 Webjar /** 访问当前项目的任何资源 欢迎页 标签页图标 Webjar 开始讲到Spring Boot的Web开发了,先介绍Webjar,这个其实就是把一些前端资源以jar包的形式导入到 ...

  7. Spring Boot笔记四:日志框架介绍

    我是一名程序员,我喜欢写System.out.println来打印一些重要的信息...后来我学了面向对象,我把这些输出语句整合到了一个工具类里面,可以打印,也可以保存日志. 我是一名积极思考的程序员, ...

  8. Spring Boot笔记一 输出hello

    开始学习Spring Boot了,本篇文章你可以学到 1.Spring Boot的基本配置,输出一句hello 许嵩 2.Spring boot打包成jar包 一.Spring boot的基本配置 这 ...

  9. Spring Boot笔记之自定义启动banner

    控制banner内容 Spring Boot启动的时候默认的banner是spring的字样,看多了觉得挺单调的,Spring Boot为我们提供了自定义banner的功能. 自定义banner只需要 ...

随机推荐

  1. (Bash博弈 大数) 51nod1068 Bash游戏 V3

    1068 Bash游戏 V3   有一堆石子共有N个.A B两个人轮流拿,A先拿.每次拿的数量只能是2的正整数次幂,比如(1,2,4,8,16....),拿到最后1颗石子的人获胜.假设A B都非常聪明 ...

  2. mac设计师系列 Adobe “全家桶” 15款设计软件 值得收藏!

    文章素材来源:风云社区.简书 文章收录于:风云社区 www.scoee.com,提供1700多款mac软件下载 Adobe Creative Cloud 全线产品均可开放下载(简称Adobe CC 全 ...

  3. python类继承的重写和super

    给已经存在的类添加新的行为,继承是非常好的实现方式.但是如果要改变行为呢?比如在Python继承扩展内置类,我们的contact类只允许一个名字和一个邮箱,但是如果要对某些人增加电话号码呢?这里可以通 ...

  4. MK-编辑器

    MK-编辑器 MarkdownPad 一款全功能的编辑器,被很多人称赞为windows 平台最好用的markdown编辑器 好用的MK编辑器:Typora 一次打开两个界面 在本文编辑器领域,Vim ...

  5. hadoop mapreduce 基础实例一记词

    mapreduce实现一个简单的单词计数的功能. 一,准备工作:eclipse 安装hadoop 插件: 下载相关版本的hadoop-eclipse-plugin-2.2.0.jar到eclipse/ ...

  6. golang interface

    接口定义 Interface类型可以定义一组方法,但是这些不需要实现.并且interface不能 包含任何变量. type Interface interface { test1(a, b int) ...

  7. jQuery使用(六):DOM操作之元素包裹、克隆DOM与data的综合应用

    包裹 wrap() wrapInner() wrapAll() unwrap() clone() 数据缓存机制 data 文档处理(包裹) 1.1.wrap()--将所匹配的元素用其他元素结构化标签包 ...

  8. Python复习笔记(十)Http协议--Web服务器-并发服务器

    1. HTTP协议(超文本传输协议) 浏览器===>服务器发送的请求格式如下:(浏览器告诉服务器,浏览器的信息) GET / HTTP/1.1 Host: www.baidu.com Conne ...

  9. 【移动端】300ms延迟以及点透事件原因以及解决方案

    产生原因 移动端会有双击缩放的这个操作,因此浏览器在click之后要等待300ms,看用户有没有下一次点击,也就是这次操作是不是双击 说完移动端点击300ms延迟的问题,还不得不提一下移动端点击穿透的 ...

  10. 爬虫基础02-day24

    写在前面 上课第24天,打卡: 努力不必让全世界知道: s16/17爬虫2 内容回顾: 1. Http协议 Http协议:GET / http1.1/r/n...../r/r/r/na=1 TCP协议 ...