SpringBoot整合数据库总结

一、 SQL:

1、配置:

1.1、导入jdbc场景

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

1.2、导入mysql驱动

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

springBoot官方已经对mysql版本进行了仲裁,可以不用写版本。

1.3、数据源配置

#数据库相关配置
spring:
  #配置数据源
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/learn?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
    username: root
    password: 123456

2、整合Druid数据源:

Druid是数据库连接池。Druid能够提供强大的监控和扩展功能。
导入jdbc场景后,springBoot会自动配置Hikari数据源,要使用Druid数据源需要重新配置DataSource。

2.1、引入druid-starter依赖

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.1.17</version>
</dependency>

2.2、配置DataSource

spring: 
	datasource: 
		druid: 
			#设置该包下的组件都得到监控
			aop-patterns: com.sunyard.*
			#开启web监控、防火墙功能
			filters: stat,wall
			#监控页配置
			stat-view-servlet: 
				#开启监控功能
				enabled: true
				#设置登录账号和密码
				login-username: admin
				login-password: admin
				#重置按钮禁用
				resetEnable: false
			#开启web监控功能
			web-stat-filter: 
				enabled: true
			filter: 
				stat: 
					#开启功能
					enabled: true
					#设置超过1秒的为慢查询
					slow-sql-millis: 1000
					#开启慢查询的监控
					logSlowSql: true
				wall: 
					#开启功能
					enabled: true
			

参考资料:
Druid中文文档:https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98

3、整合MyBatis:

3.1、引入mybatis-spring-boot-starter

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.4</version>
</dependency>

3.2、MyBatis配置

#MyBatis相关配置
#配置映射文件
mybatis: 
	mapper-locations: classpath*:mappers/*.xml
	type-aliases-package: com.example.TestNew.entity  # 注意:对应实体类的路径
	configuration: 
		#开启驼峰命名
		map-underscore-to-camel-case: true

然后编写mapper接口即可操作数据库。

3、整合MyBatis-Plus:

3.1、引入mybatis-plus-boot-starter

<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.4.1</version>
</dependency>

配置的话…mybatis-plus把一切都配置好了,包括映射文件路径、开启驼峰命名等,所以可以直接用。

3.2、编写mapper接口

public interface UserMapper extends BaseMapper<User> {
}

继承BaseMapper后就可以实现许多基础的增删改查功能,User为要操作的实体类。

3.3、编写service

@Service
public interface UserService extends IService<User> {
}
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {
}

ServiceImpl提供了许多复杂的数据库操作方法。

3.4、QueryWrapper条件构造器
mybatis-plus提供了很多关于区间查询,多表连接查询,分组等等查询功能,使用这些功能时,只需要创建QueryWrapper对象即可。

使用示例:

QueryWrapper<SanyOrder> queryWrapper1 = new QueryWrapper<SanyOrder>();
queryWrapper1.select("xing_customer_id").eq("order_no", cibComingDataReq.getOrderNo());
SanyOrder sanyOrder = sanyOrderMapper.selectOne(queryWrapper1);

3.5、Lambda条件构造器

QueryWrapper是通过自己写表中相应的属性进行构造where条件的,容易发生拼写错误,在编译时不会报错,只有运行时才会报错,而lambda条件构造器是通过调用实体类中的方法,如果方法名称写错,直接进行报错,所以lambda的纠错功能比QueryWrapper要提前很多。

mybatis-plus提供了多种方法创建Lambda条件构造器:

LambdaQueryWrapper<User> lambdaQueryWrapper = new QueryWrapper<User>().lambda();
LambdaQueryWrapper<User> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();

使用示例:

LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.like(User::getName,"雨").lt(User::getAge,40);
List<User> userList = userMapper.selectList(lambdaQueryWrapper);

不过这样使用的话每次编写完条件构造语句后都要将对象传递给mapper 的select方法,比较麻烦,如下使用会简单许多:

List<User> userList = new LambdaQueryChainWrapper<>(userMapper).like(User::getName, "雨").ge(User::getAge, 20).list();

3.6、分页查询

新建配置类:

@Configuration
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}

建好配置类之后就可以使用分页查询了:

QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.ge("age",20);

//设置当前页和页容量
Page<User> page = new Page<>(1, 2);

IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);

System.out.println("总页数:"+userIPage.getPages());
System.out.println("总记录数:"+userIPage.getTotal());
userIPage.getRecords().forEach(System.out::println);

3.7、AR模式

编写实体类:

@Data
@EqualsAndHashCode(callSuper = false)
public class User extends Model<User> {
}

实体类要继承Model类,Model类中封装了很多增删改查方法,不用使用UserMapper即可完成对数据的增删改查。

使用示例:

User user = new User();
//查询所有用户信息
user.selectAll().forEach(System.out::println);

参考文章:

MyBatis整理:
https://www.jianshu.com/p/12ec123d20e8

二、NoSQL:

1、整合Redis

1.1、引入spring-boot-starter-data-redis

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

1.2、配置文件

redis:
	host: {地址}
	port: {端口号}
	password: {账号}:{密码}

1.3、配置类

@Configuration
@EnableCaching //开启注解
public class RedisConfig {

    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        //配置连接工厂
        template.setConnectionFactory(factory);
        //设置序列化和反序列化方案
        template.setKeySerializer(new GenericJackson2JsonRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

1.4、使用方法

ValueOperations<String, String> operations = redisTemplate.opsForValue();
operations.set("hello", "world");
log.init(operations.get("hello"));

Redis自动配置了两个Bean:
​ RedisTemplate:操作key-value都是对象的。
​ StringRedisTemplate:操作key-value都是字符串的。

Redis常见的五大数据类型:String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)

  • stringRedisTemplate.opsForValue() :【用于操作String(字符串)】
  • stringRedisTemplate.opsForList() :【用于操作List(列表)】
  • stringRedisTemplate.opsForSet() :【用于操作Set(集合)】
  • stringRedisTemplate.opsForHash() :【用于操作Hash(散列)】
  • stringRedisTemplate.opsForZSet() :【用于操作ZSet(有序集合)】

参考文章:

Redis简单配置与使用:
https://www.jianshu.com/p/b9154316227e

RedisTemplate操作Redis数据库:
https://blog.csdn.net/lydms/article/details/105224210

中文乱码解决:
https://blog.csdn.net/qqqqqqq123_er/article/details/101367531

Redis序列化LocalDataTime的问题:
https://blog.csdn.net/lqbz456/article/details/106193541/

LocalDateTime具体使用:
https://blog.csdn.net/kingboyworld/article/details/75808108

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值