SpringBoot整合其他框架

1 SpringBoot 整合 Mybatis

SQL脚本

-- 使用 source 命令可运行 SQL 脚本,如 "source /tmp/test.sql;"

create database if not exists test character set utf8;
use test;

DROP TABLE IF EXISTS `t_users`;
CREATE TABLE `t_users`(
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL DEFAULT '',
  `gender` tinyint(4) NOT NULL DEFAULT '0' COMMENT '//1 male,2 female',
  `age` int(11) NOT NULL DEFAULT '0',
  `telphone` varchar(255) NOT NULL DEFAULT '',
  `register_mode` varchar(255) NOT NULL DEFAULT '' COMMENT '//byphone,bywechat,byalipay',
  `third_party_id` varchar(64) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `telphone_unique_index` (`telphone`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;

INSERT INTO `t_users` VALUES(1,'zhangsan',1,30,'18362610001','byphone','');
INSERT INTO `t_users` VALUES(15,'lisi',1,20,'18362610002','byphone','');
INSERT INTO `t_users` VALUES(20,'wangwu',1,1,'18362610003','byphone','');
INSERT INTO `t_users` VALUES(21,'zhaoliu',1,31,'18362610004','byphone','');
INSERT INTO `t_users` VALUES(22,'xiaohong',2,20,'18362610005','byphone','');


DROP TABLE IF EXISTS `t_users_password`;
CREATE TABLE `t_users_password` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `encrpt_password` varchar(128) NOT NULL DEFAULT '',
  `user_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;

INSERT INTO `t_users_password` VALUES(1,'e10adc3949ba59abbe56e057f20f883e',1);
INSERT INTO `t_users_password` VALUES(2,'e10adc3949ba59abbe56e057f20f883e',15);
INSERT INTO `t_users_password` VALUES(3,'e10adc3949ba59abbe56e057f20f883e',20);
INSERT INTO `t_users_password` VALUES(4,'e10adc3949ba59abbe56e057f20f883e',21);
INSERT INTO `t_users_password` VALUES(5,'e10adc3949ba59abbe56e057f20f883e',22);

步骤

  1. 创建普通 maven 项目,导入依赖

    <!-- mysql 依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>
    <!-- mybatis 依赖 -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.3</version>
    </dependency>
    <!-- lombok 依赖 -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
    </dependency>
    <!-- 测试类依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>2.5.6</version>
    </dependency>
    
  2. 编写配置文件 application.yml

    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: root
        url: jdbc:mysql://192.168.192.129:3306/test?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false
    
    mybatis:
      configuration:
        map-underscore-to-camel-case: true # 开启驼峰映射
    
  3. 编写持久层代码

    package cn.mybatis;
    
    import lombok.Data;
    
    @Data
    public class UsersDO {
        private Integer id;
        private String name;
        private byte gender;
        private Integer age;
        private String telphone;
        private String registerMode;
        private String thirdPartyId;
    }
    
    package cn.mybatis;
    
    import lombok.Data;
    
    @Data
    public class UsersPasswordDO {
        private Integer id;
        private String encrptPassword;
        private Integer userId;
    }
    
    package cn.mybatis;
    
    import org.apache.ibatis.annotations.Select;
    
    public interface UsersMapper {
        @Select("select id, name, gender, age, telphone, register_mode, third_party_id from t_users where id = #{uid}")
        UsersDO findUserById(Integer uid);
    }
    
    package cn.mybatis;
    
    import org.apache.ibatis.annotations.Select;
    
    public interface UserPasswordMapper {
        @Select("select id, encrpt_password, user_id from t_users_password where user_id = #{uid}")
        UsersPasswordDO findPasswordById(Integer uid);
    }
    
  4. 编写启动类

    package cn;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @MapperScan("cn/mybatis")
    @SpringBootApplication
    public class App {
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }
    
  5. 编写测试类

    package cn.mybatis;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import javax.annotation.Resource;
    
    @SpringBootTest
    public class MyBatisTest {
    
        @Resource
        private UsersMapper usersMapper;
        @Resource
        private UserPasswordMapper userPasswordMapper;
    
        @Test
        public void test() {
            UsersDO usersDO = usersMapper.findUserById(1);
            System.out.println("usersDO = " + usersDO);
            UsersPasswordDO usersPasswordDO = userPasswordMapper.findPasswordById(1);
            System.out.println("usersPasswordDO = " + usersPasswordDO);
            /**
             * 开启驼峰配置前结果
             * usersDO = UsersDO(id=1, name=zhangsan, gender=1, age=30, telphone=18362610001, registerMode=null, thirdPartyId=null)
             * usersPasswordDO = UsersPasswordDO(id=1, encrptPassword=null, userId=null)
             *
             * 开启驼峰配置后结果
             * usersDO = UsersDO(id=1, name=zhangsan, gender=1, age=30, telphone=18362610001, registerMode=byphone, thirdPartyId=)
             * usersPasswordDO = UsersPasswordDO(id=1, encrptPassword=e10adc3949ba59abbe56e057f20f883e, userId=1)
             */
        }
    }
    

2 SpringBoot 整合 JPA

步骤(整体框架基于上面整合mybatis)

  1. 依赖

    <!-- jpa 依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>2.5.6</version>
    </dependency>
    
  2. application.yml

    spring:
      # 数据源配置同上面mybatis、略,下面配置为显示SQL语句
      jpa:
        show-sql: true
    
  3. 持久层代码

    package cn.jpa;
    
    import lombok.Data;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "t_users")
    @Data
    public class UsersEntity {
        @Id
        @Column(name = "id")
        private Integer id;
        @Column(name = "name")
        private String name;
        @Column(name = "gender")
        private byte gender;
        @Column(name = "age")
        private Integer age;
        @Column(name = "telphone")
        private String telphone;
        @Column(name = "register_mode") //数据库字段
        private String registerMode;
        @Column(name = "third_party_id")
        private String thirdPartyId;
    
    }
    
    package cn.jpa;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UsersRepository extends JpaRepository<UsersEntity, Integer> {
        
    }
    
  4. 测试

    package cn.jpa;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import javax.annotation.Resource;
    import javax.transaction.Transactional;
    
    @SpringBootTest
    public class JpaTest {
        @Resource
        private UsersRepository usersRepository;
    
        @Test
        @Transactional // no Session 异常加事务注解
        public void test() {
            UsersEntity usersEntity = usersRepository.getById(1);
            System.out.println(usersEntity);
        }
        /**
         * 显示的SQL语句(已做格式化处理)
         * select
         *   usersentit0_.id as id1_0_0_,
         *   usersentit0_.age as age2_0_0_,
         *   usersentit0_.gender as gender3_0_0_,
         *   usersentit0_.name as name4_0_0_,
         *   usersentit0_.register_mode as register5_0_0_,
         *   usersentit0_.telphone as telphone6_0_0_,
         *   usersentit0_.third_party_id as third_pa7_0_0_
         * from
         *   t_users usersentit0_
         * where
         *   usersentit0_.id = ?
         *
         * 结果
         * UsersEntity(id=1, name=zhangsan, gender=1, age=30, telphone=18362610001, registerMode=byphone, thirdPartyId=)
         */
    }
    

3 SpringBoot 整合 Redis

步骤(整体框架基于上面整合mybatis)

  1. 导入依赖

    <!-- redis 依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <version>2.5.6</version>
    </dependency>
    <!-- json 依赖(修改redis默认序列化方式时需要用到) -->
    <!-- 若是项目中还有其他spring系列依赖时,下面三个有可能会默认引入,当报错时再引入下面三个 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.11.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.11.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.11.3</version>
    </dependency>
    
  2. application.yml

    spring:
      redis:
        host: 192.168.192.129
        port: 6379
        password: 123456
        database: 1
        jedis:
          pool:
            max-active: 8
            max-idle: 8
            min-idle: 0
            max-wait: 1000
    
  3. 修改redis默认序列化方式

    package cn.redis;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            // 使用Jackson2JsonRedisSerialize 替换默认序列化
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
            // 设置key和value的序列化规则
            redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
            redisTemplate.afterPropertiesSet();
            return redisTemplate;
        }
    }
    
  4. 测试

    package cn.redis;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    
    import javax.annotation.Resource;
    
    @SpringBootTest
    public class RedisTest {
        @Resource
        private RedisTemplate redisTemplate;
    
        @Test
        public void test() {
            redisTemplate.opsForValue().set("phone", "18362610001");
            redisTemplate.opsForValue().set("gender", "male");
            System.out.println(redisTemplate.opsForValue().get("phone"));
            System.out.println(redisTemplate.opsForValue().get("gender"));
            /**
             * 结果
             * 18362610001
             * male
             */
        }
    }
    
    # 进入 redis 客户端查看结果
    [root@localhost redis5]# bin/redis-cli -a 123456
    Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
    127.0.0.1:6379> select 1
    OK
    127.0.0.1:6379[1]> keys *
    1) "gender"
    2) "phone"
    127.0.0.1:6379[1]> get gender
    "\"male\""
    127.0.0.1:6379[1]> get phone
    "\"18362610001\""
    
posted @ 2021-11-10 23:46  lkf-newlife  阅读(58)  评论(0编辑  收藏  举报