0
点赞
收藏
分享

微信扫一扫

超详细的SpringBoot整合第三方技术(含整合MyBatis、Redis、JPA、Junit)

五、SpringBoot与整合其他技术

5.1 SpringBoot整合Mybatis

5.1.1 搭建工程

5.1.1.1 依赖:

<?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.dfbz</groupId>
    <artifactId>04-SpringBoot-MyBatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <artifactId>spring-boot-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.0.1.RELEASE</version>
    </parent>

    <dependencies>
        <!--mybatis起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <!-- MySQL连接驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
</project>

5.1.1.2 创建实体Bean

package com.dfbz.entity;

/**
* @author lscl
* @version 1.0
* @intro:
*/
public class User {
   private Integer id;
   private String username;
   private String password;
   private String name;

   @Override
   public String toString() {
       return "User{" +
               "id=" + id +
               ", username='" + username + '\'' +
               ", password='" + password + '\'' +
               ", name='" + name + '\'' +
               '}';
   }

   public Integer getId() {
       return id;
   }

   public void setId(Integer id) {
       this.id = id;
   }

   public String getUsername() {
       return username;
   }

   public void setUsername(String username) {
       this.username = username;
   }

   public String getPassword() {
       return password;
   }

   public void setPassword(String password) {
       this.password = password;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }
}

5.1.1.3 application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: admin
#spring集成Mybatis环境
mybatis:
  type-aliases-package: com.dfbz.entity  #pojo别名扫描包
  #加载Mybatis映射文件
  mapper-locations: classpath:com/dfbz/mapper/*Mapper.xml

5.1.1.4 UserMapper

package com.dfbz.dao;

import com.dfbz.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@Mapper
public interface UserMapper {
    public List<User> findAll();
}

5.1.1.5 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.dfbz.mapper.UserMapper">
    <select id="findAll" resultType="user">
        select * from user
    </select>
</mapper>

5.1.2 创建表

/*Table structure for table `user` */
CREATE TABLE `user` (
 `id` INT(11) NOT NULL AUTO_INCREMENT,
 `username` VARCHAR(50) DEFAULT NULL,
 `password` VARCHAR(50) DEFAULT NULL,
 `name` VARCHAR(50) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

/*Data for the table `user` */
INSERT  INTO `user`(`id`,`username`,`password`,`name`) VALUES (1,'zhangsan','123','张三');
INSERT  INTO `user`(`id`,`username`,`password`,`name`) VALUES (2,'lisi','123','李四');

5.1.3 测试

5.1.3.1 Controller

@RestController
public class UserController {
    
    @Autowired
    private UserMapper userMapper;
    
    @RequestMapping("/findAll")
    public List<User> findAll(){
       return userMapper.findAll();
    }
}

访问:http://localhost:8080/findAll:

超详细的SpringBoot整合第三方技术(含整合MyBatis、Redis、JPA、Junit)_springboot

5.2 SpringBoot整合Junit

5.2.1 添加Junit的场景启动器

<!--springboot集成junit起步依赖-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

5.2.2 编写测试类

package com.dfbz.demo;

import com.dfbz.Application;
import com.dfbz.entity.User;
import com.dfbz.mapper.UserMapper;
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 java.util.List;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes= Application.class)
public class Demo01 {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test1(){

        List<User> userList = userMapper.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

5.3 SpringBoot整合Spring Data JPA

5.3.1 添加Spring Data JPA的起步依赖

<!-- springBoot JPA的起步依赖 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

5.3.2 jpa相关配置

spring:
  #JPA 配置信息:
  jpa:
    show-sql: true
    database: mysql
    hibernate:
      ddl-auto: update
    generate-ddl: true

5.3.3 建立映射

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@Entity
@Table(name = "user")
public class User {

    //主键
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    //用户名
    private String username;
    //密码
    private String password;
    //姓名
    private String name;
}

5.3.3 编写UserDao

public interface UserDao extends JpaRepository<User,Integer>{
}

5.3.4 编写测试类

package com.dfbz.demo;

import com.dfbz.Application;
import com.dfbz.dao.UserDao;
import com.dfbz.entity.User;
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 java.util.List;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes= Application.class)
public class Demo02_JPA {

    @Autowired
    private UserDao userDao;

    @Test
    public void test1(){

        List<User> userList = userDao.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

5.4 SpringBoot整合Redis

Key类型操作

ValueOperations

Redis String/Value 操作

ListOperations

Redis List 操作

SetOperations

Redis Set 操作

ZSetOperations

Redis Sort Set 操作

HashOperations

Redis Hash 操作

Value约束操作

BoundValueOperations

Redis String/Value key 约束

BoundListOperations

Redis List key 约束

BoundSetOperations

Redis Set key 约束

BoundZSetOperations

Redis Sort Set key 约束

BoundHashOperations

Redis Hash key 约束

  • GenericJackson2JsonRedisSerializer:Value序列化
  • StringRedisSerializer:Key序列化

5.4.1 添加Redis的起步依赖

<!-- 配置使用redis启动器 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

5.4.2 Redis相关配置

spring:
  redis:
    host: localhost
    port: 6379
    password: admin

5.4.3 测试类

package com.dfbz.demo;


import com.dfbz.Application;
import com.dfbz.entity.User;
import com.dfbz.mapper.UserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
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.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.List;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class Demo03_Redis {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void test1() throws IOException {

        BoundValueOperations<String, String> bvo = redisTemplate.boundValueOps("userList");
        String val = bvo.get();

        ObjectMapper om = new ObjectMapper();

        //第一次从数据库读取
        if (val == null) {
            List<User> userList = userMapper.findAll();

            val = om.writeValueAsString(userList);

            System.out.println("从数据库读出来的: " + val);
            bvo.set(val);
        } else {
            System.out.println("从redis读取:");

            System.out.println(val);
        }
    }
}

举报

相关推荐

0 条评论