• spring boot 笔记1


    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,有待进一步了解。

  • 相关阅读:
    django之admin管理工具
    django之中间件
    cookie和session
    day052-53 django框架
    day050 前端Jquery库的使用
    sprint
    Scrum 项目1.0
    【团队项目】3.0
    [读书笔记]
    【团队项目】2.0
  • 原文地址:https://www.cnblogs.com/lanqie/p/9008536.html
Copyright © 2020-2023  润新知