概述

在开发中,通常会涉及到对数据库的数据进行操作,Spring Boot在简化项目开发以及实现自动化配置的基础上,对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持。

Spring Boot默认采用整合SpringData的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,从而达到简化数据访问层的操作。

常见数据库依赖启动器

整合MyBatis

基础环境搭建

创建数据库、数据表并插入一定的数据

CREATE DATABASE `springbootdata`;USE `springbootdata`;CREATE TABLE `t_article` (`id` int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',`title` varchar(200) DEFAULT NULL COMMENT '文章标题',`content` longtext COMMENT '文章内容',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');CREATE TABLE `t_comment` (`id` int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',`content` longtext COMMENT '评论内容',`author` varchar(200) DEFAULT NULL COMMENT '评论作者',`a_id` int(20) DEFAULT NULL COMMENT '关联的文章id',PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;INSERT INTO `t_comment` VALUES ('1', '很全、很详细', '狂奔的蜗牛', '1');
INSERT INTO `t_comment` VALUES ('2', '赞一个', 'tom', '1');
INSERT INTO `t_comment` VALUES ('3', '很详细', 'kitty', '1');
INSERT INTO `t_comment` VALUES ('4', '很好,非常详细', '张三', '1');
INSERT INTO `t_comment` VALUES ('5', '很不错', '张杨', '2');

创建项目,引入MySQL和MyBatis依赖

使用Spring Starter Project的方式构建项目,选择MySQL和MyBatis依赖

<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.2</version>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId>
</dependency>

创建com.itheima.domain包,及CommentArticle实体类

public class Comment {private Integer id;private String content;private String author;private Integer aId;//添加set 、get、 toString}
public class Article {private Integer id;private String title;private String content;private List<Comment> commentList;//添加set 、get、 toString}

编写配置文件:

在application.properties中添加数据库连接配置和第三方数据源配置

spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root#可以不用配置,因为用了druid-spring-boot-starter,项目会自动识别该数据源
spring.datasource.type = com.alibaba.druid.pool.DruidDataSourcespring.datasource.initialSize=20
spring.datasource.minIdle=10
spring.datasource.maxActive=100

在pom文件中添加Druid数据源依赖

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

建com.itheima.config包,DataSourceConfig配置类

你会发现下面这些属性无法识别

spring.datasource.initialSize=20
spring.datasource.minIdle=10
spring.datasource.maxActive=100

因为springboot提供的数据源自动配置类DataSourceProperties没有与这些参数对应的默认属性值,所以这些设置的属性值无法识别和生效,所以需要自定义配置类,把配置属性注入到数据源属性中

@Configuration
public class DataSourceConfig {@Bean@ConfigurationProperties(prefix = "spring.datasource")public DataSource getDruid() {return new DruidDataSource();}}

测试是否注入成功

@Autowired
private DruidDataSource dataSource;@Test
public void testDruidDataSource() {System.out.println(dataSource.getMaxActive());}

使用注解方式访问数据

1.创建包名及Mapper接口文件:

com.itheima.mapper

@Mapper
public interface CommentMapper {@Select("SELECT * FROM t_comment WHERE id =#{id}")public Comment findById(Integer id);@Insert("INSERT INTO t_comment(content,author,a_id) " +
"values (#{content},#{author},#{aId})")public int insertComment(Comment comment);@Update("UPDATE t_comment SET content=#{content} WHERE id=#{id}")public int updateComment(Comment comment);@Delete("DELETE FROM t_comment WHERE id=#{id}")public int deleteComment(Integer id);}

提示:如果接口文件过多,可以在启动类上添加@MapperScan(“接口文件所在的包名”),不必再接口文件上添加@Mapper.

2.编写测试方法进行整合测试

控制台显示SQL:

logging.level.你的Mapper包=日志等级

例如:logging.level.com.itheima.myblog.mapper=debug

@Autowired
//会报错,但不影响执行,可以在Mapper接口中添加//@Component(“commentMapper”)
private CommentMapper commentMapper;@Test
public void selectComment() {Comment comment = commentMapper.findById(1);System.out.println(comment);}

关联对象没有查询出来,如下图

原因:实体类叫aId,数据表叫a_id,名称不一致,导致映射不成功。

解决方法:因为aId按驼峰命名的,所以开启驼峰命名匹配映射  mybatis.configuration.map-underscore-to-camel-case=true

使用配置文件方式访问数据

1.创建Mapper接口文件:@Mapper

@Mapper
public interface ArticleMapper {public Article selectArticle(Integer id);public int updateArticle(Article article);}

2.创建XML映射文件:编写对应的SQL语句

创建文件夹mapper,不是资源文件夹,如下图

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.itheima.mapper.ArticleMapper"><!-- 1、查询文章详细(包括评论信息) --><select id="selectArticle" resultMap="articleWithComment">SELECT a.*,c.id c_id,c.content c_content,c.authorFROM t_article a,t_comment cWHERE a.id=c.a_id AND a.id = #{id}</select><resultMap id="articleWithComment" type="Article"><id property="id" column="id" /><result property="title" column="title" /><result property="content" column="content" /><collection property="commentList" ofType="Comment"><id property="id" column="c_id" /><result property="content" column="c_content" /><result property="author" column="author" /></collection></resultMap><!-- 2、根据文章id更新文章信息 --><update id="updateArticle" parameterType="Article">UPDATE t_article<set><if test="title !=null and title !=''">    title=#{title},</if><if test="content !=null and content !=''">content=#{content}</if></set>WHERE id=#{id}
</update></mapper>

3.在全局文件中配置XML映射文件路径以及实体类别名映射路径

#配置MyBatisxml配置文件路径

mybatis.mapper-locations=classpath:mapper/*.xml

#设置XML映射文件中的实体类别名的路径

mybatis.type-aliases-package=com.itheima.domain

4.编写测试方法进行整合测试

@Autowired
private ArticleMapper articleMapper;@Test
public void selectArticle() {Article article = articleMapper.selectArticle(1);System.out.println(article);}

Spring Boot 整合JPA

Spring Data JPA是Spring基于ORM框架、JPA规范的基础上封装的一套JPA应用框架,它提供了增删改查等常用功能,使开发者可以用较少的代码实现数据操作,同时还易于扩展。

Spring Data JPA介绍

1、编写ORM实体类:实体类与数据表进行映射,并且配置好映射关系。

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity(name = "t_comment")
public class Discuss {@Id@GeneratedValue(strategy =GenerationType.IDENTITY)private Integer id;@Column(name = "a_id")private Integer aId;// 省略getXX()和setXX()方法}

2、编写Repository接口:

针对不同的表数据操作编写各自对应的Repositor接口,并根据需要编写对应的数据操作方法。

编写Repository接口DiscussRepository

//查询author非空的Discuss评论信息
public List<Discuss> findByAuthorNotNull();//通过文章id分页查询出Discuss评论信息。
@Query("SELECT c FROM t_comment c WHERE c.aId = ?1") //JPQL
public List<Discuss> getDiscussPaged(Integer aid,Pageable pageable);//通过文章id分页查询出Discuss评论信息。
@Query(value = "SELECT * FROM t_comment  WHERE  a_Id = ?1",nativeQuery = true)//原生sql
public List<Discuss> getDiscussPaged2(Integer aid,Pageable pageable);//对数据进行更新和删除操作
@Transactional
@Modifying
@Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2")
public int updateDiscuss(String author,Integer id);  @Transactional
@Modifying
@Query("DELETE t_comment c WHERE c.id = ?1")
public int deleteDiscuss(Integer id);

注:

  • getDiscussPaged2与getDiscussPaged()方法的参数和作用完全一样。
  • 区别是该方法上方的@Query注解将nativeQuery属性设置为了true,用来编写原生SQL语句。

Repository继承关系

使用Spring Data JPA自定义Repository接口,必须继承XXRepository<T, ID>接口。

T:实体类

ID:实体类中主键对应的属性的数据类型

使用Spring Data JPA进行数据操作的多种实现方式

1、如果自定义接口继承了JpaRepository接口,则默认包含了一些常用的CRUD方法。

2、自定义Repository接口中,可以使用@Query注解配合SQL语句进行数据的查、改、删操作。

3、自定义Repository接口中,可以直接使用关键字构成的方法名进行查询操作。

@Transactional注解

  • 在自定义的Repository接口中,针对数据的变更操作(修改、删除),无论是否使用了@Query注解,都必须在方法上方添加@Transactional注解进行事务管理,否则程序执行就会出现InvalidDataAccessApiUsageException异常。
  • 如果在调用Repository接口方法的业务层Service类上已经添加了@Transactional注解进行事务管理,那么Repository接口文件中就可以省略@Transactional注解。

变更操作,要配合使用@Query与Modify注解

  • 在自定义的Repository接口中,使用@Query注解方式执行数据变更操作(修改、删除),除了要使用@Query注解,还必须添加@Modifying注解表示数据变更。

使用Example实例进行复杂条件查询

整合步骤

0.在全局配置文件中添加数据库配置

spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=zptc1234

1.在pom文件中添加Spring Data JPA依赖启动器

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

2.编写ORM实体类

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity(name = "t_comment")
public class Discuss {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;private String content;private String author;@Column(name = "a_id")private Integer aId;//补上get、set、toString方法}

3.编写Repository接口

创建包com.itheima.repository,及接口DiscussRepository

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;public interface DiscussRepository extends JpaRepository<Discuss, Integer>{//查询author非空的Discuss评论信息public List<Discuss> findByAuthorNotNull();//通过文章id分页查询出Discuss评论信息。JPQL@Query("SELECT c FROM t_comment c WHERE c.aId = ?1")public List<Discuss> getDiscussPaged(Integer aid,Pageable pageable);  //通过文章id分页查询出Discuss评论信息。原生sql@Query(value = "SELECT * FROM t_comment  WHERE  a_Id = ?1",nativeQuery = true)public List<Discuss> getDiscussPaged2(Integer aid,Pageable pageable);//对数据进行更新和删除操作@Transactional@Modifying@Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2")public int updateDiscuss(String author,Integer id);  @Transactional@Modifying@Query("DELETE t_comment c WHERE c.id = ?1")public int deleteDiscuss(Integer id);
}

4.编写单元测试

@SpringBootTest
class JpaTests {@Autowiredprivate DiscussRepository repository;//使用JpaRepository内部方法@Testpublic void selectComment() {Optional<Discuss>optional = repository.findById(1);if (optional.isPresent()) {System.out.println(optional.get());}}//使用方法名关键字进行数据操作@Testpublic void selectCommentByKeys() {List<Discuss>list = repository.findByAuthorNotNull();for (Discuss discuss : list) {System.out.println(discuss);}}//使用@Query注解@Testpublic void selectCommentPaged() {Pageable page = PageRequest.of(0, 3);List<Discuss>list = repository.getDiscussPaged(1, page);System.out.println(list);}//使用Example封装参数,精确匹配查询条件@Testpublic void selectCommentByExample() {Discuss discuss=new Discuss();discuss.setAuthor("张三");Example<Discuss>example = Example.of(discuss);List<Discuss>list = repository.findAll(example);System.out.println(list);}//使用ExampleMatcher模糊匹配查询条件@Testpublic void selectCommentByExampleMatcher() {Discuss discuss=new Discuss();discuss.setAuthor("张");ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("author",                     ExampleMatcher.GenericPropertyMatcher.of(ExampleMatcher.StringMatcher.CONTAINING));Example<Discuss>example = Example.of(discuss, matcher);List<Discuss>list = repository.findAll(example);System.out.println(list);}//保存评论@Testpublic void saveDiscuss() {Discuss discuss=new Discuss();discuss.setAuthor("张he");repository.save(discuss);}//更新作者@Testpublic void updateDiscuss() {repository.updateDiscuss("更新者", 1);}//删除评论@Testpublic void deleteDiscuss() {repository.deleteDiscuss(5);}}

查询方法定义规范

简单查询条件 :查询某一个实体类或是集合
在Repository 子接口中声明方法:
①、不是随便声明的,而需要符合一定的规范
②、查询方法以 find | read | get 开头
③、涉及条件查询时,条件的属性用条件关键字连接
④、要注意的是:条件属性以首字母大写
⑤、支持属性的级联查询。若当前类有符合条件的属性,则优先使用,而不使用级联属性。若需要使用级联属性,则属性之间使用_连接

springboot整合redis

Redis 介绍

简介:Redis 是一个开源(BSD许可)的、内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,并提供多种语言的API。

优点:

  1. 存取速度快:Redis速度非常快,每秒可执行大约110000次的设值操作,或者执行81000次的读取操作。
  2. 支持丰富的数据类型:Redis支持开发人员常用的大多数数据类型,例如列表、集合、排序集和散列等。
  3. 操作具有原子性:所有Redis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新后的值。
  4. 提供多种功能:Redis提供了多种功能特性,可用作非关系型数据库、缓存中间件、消息中间件等。

下载安装

redis服务开启和连接配置

双击开启服务

双击打开可视化的客户端

打开redis连接配置窗口

连接名字自定义,主机127.0.0.1

整合步骤

1.在pom文件中添加spring-boot-starter-data-redis依赖启动器

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

2.编写三个实体类

@RedisHash("persons")  // 指定操作实体类对象在Redis数据库中的存储空间
public class Person {@Id// 标识实体类主键private String id;// 标识对应属性在Redis数据库中生成二级索引,索引名就是属性名,可以方便地进行数据条件查询@Indexedprivate String firstname;@Indexedprivate String lastname;private Address address;private List<Family>familyList;public Person() {    }public Person(String firstname, String lastname) {this.firstname = firstname;this.lastname = lastname;}//补充get set toString}
public class Address {@Indexedprivate String city;@Indexedprivate String country;public Address() {}public Address(String city, String country) {this.city = city;this.country = country;}//补充get set toString}
public class Family {@Indexedprivate String type;@Indexedprivate String username;public Family() {    }public Family(String type, String username) {this.type = type;this.username = username;}//补充get set toString}

3.编写Repository接口

public interface PersonRepository extends CrudRepository<Person, String> {List<Person> findByLastname(String lastname);Page<Person> findPersonByLastname(String lastname, Pageable page);List<Person> findByFirstnameAndLastname(String firstname, String lastname);List<Person> findByAddress_City(String city);List<Person> findByFamilyList_Username(String username);}

4.在全局配置文件application.properties中添加Redis数据库连接配置

# Redis服务器地址
spring.redis.host=127.0.0.1# Redis服务器连接端口
spring.redis.port=6379# Redis服务器连接密码(默认为空)
spring.redis.password=

5.编写单元测试进行接口方法测试以及整合测试

@SpringBootTest
public class RedisTests {@Autowiredprivate PersonRepository repository;@Testpublic void savePerson() {Person person =new Person("张","有才");Person person2 =new Person("James","Harden");// 创建并添加住址信息Address address=new Address("北京","China");person.setAddress(address);// 创建并添加家庭成员List<Family>list =new ArrayList<>();Family dad =new Family("父亲","张良");Family mom =new Family("母亲","李香君");list.add(dad);list.add(mom);person.setFamilyList(list);// 向Redis数据库添加数据Person save = repository.save(person);Person save2 = repository.save(person2);System.out.println(save);System.out.println(save2);}@Testpublic void selectPerson() {List<Person>list = repository.findByAddress_City("北京");System.out.println(list);}@Testpublic void updatePerson() {Person person = repository.findByFirstnameAndLastname("张","有才").get(0);person.setLastname("小明");Person update = repository.save(person);System.out.println(update);}@Testpublic void deletePerson() {Person person = repository.findByFirstnameAndLastname("张","小明").get(0);repository.delete(person);}}

作业:

springboot整合mybatis ,使用注解方式访问数据

3-Spring Boot的数据访问相关推荐

  1. Spring Boot与数据访问

    Spring Boot与数据访问 JBDC.MyBatis.Spring Data JPA 一.简介 对于数据访问层,无论是SQL还是NOSQL,Spring Boot默认采用整合 Spring Da ...

  2. Spring boot(6) 数据访问

    Spring boot(6) 数据访问 学习视频:https://www.bilibili.com/video/BV19K4y1L7MT?p=62&spm_id_from=pageDriver ...

  3. Spring Boot - 构建数据访问层

    文章目录 基础规范: JDBC 关系型数据库访问规范 JDBC 规范中的核心编程对象 DriverManager DataSource Connection Statement/PreparedSta ...

  4. 有关计算机文献的外文和翻译,【精品文档】关于计算机专业有关的外文文献翻译成品:Spring Boot的数据访问(中英文双语对照)19.docx...

    此文档是毕业设计外文翻译成品( 含英文原文+中文翻译),无需调整复杂的格式!下载之后直接可用,方便快捷!本文价格不贵,也就几十块钱!一辈子也就一次的事! 外文标题:Data Access with S ...

  5. Spring Boot解决无法访问图片的问题

    Spring Boot解决无法访问图片的问题 参考文章: (1)Spring Boot解决无法访问图片的问题 (2)https://www.cnblogs.com/yang101/p/11442802 ...

  6. 使用Spring JDBC进行数据访问 (JdbcTemplate/NamedParameterJdbcTemplate/SimpleJdbcTemplate/SimpleJdbcCall/Stor)

    http://www.cnblogs.com/webcc/archive/2012/04/11/2442680.html 使用Spring JDBC进行数据访问 11.1. 简介 Spring JDB ...

  7. 护网必备技能:Spring Boot 接口数据加解密 功能实现

    护网必备技能:Spring Boot 接口数据加解密 功能实现 文章目录 护网必备技能:Spring Boot 接口数据加解密 功能实现 1. 尽量少改动,不影响之前的业务逻辑: 2. 考虑到时间紧迫 ...

  8. Spring Boot 配置 HTTPS 访问

    Spring Boot 配置 HTTPS 访问 相关代码 生成证书 创建新证书 keytool -genkeypair -alias hellowood -keyalg RSA -keysize 20 ...

  9. Java工作笔记-Spring Boot + Jdbc + dm7Driver访问数据库(Spring Boot连接达梦数据库)

    目录 基本概念 代码与实例 基本概念 Jdbc有4种方式访问数据库,下面给出达梦访问数据库的方式. 安装好达梦库后,就会有驱动,在此不再说明怎么去安装! 本次使用Java7的环境,所以使用的Jar包为 ...

最新文章

  1. jenkins自动化工具使用教程(转)
  2. debian 8 网桥
  3. c语言 #define dpath .exe是什么意思,C语言宏定义#define
  4. SQL Server 跨库同步数据
  5. Cucumber 入门一
  6. uimsbf和 bslbf的含义
  7. windows 2012 r2 can't find kb2919355
  8. 开源原生JavaScript插件-CJPCD(省市区联动)
  9. EDUCoder编程练习题解(一维数组和二维数组)
  10. linux+git登陆,图解如何在Linux上配置git自动登陆验证
  11. GIMP教程 2 文字工具
  12. [LOJ2339][虚树][边分治][树形DP]WC2018:通道
  13. u盘安装红旗linux操作系统,如何用u盘安装红旗linux?
  14. tensorflow的GPU加速计算
  15. python 录音_python实现录音功能(可随时停止录音)
  16. 利用JS来设计夜场的倒计时以及进入页面
  17. hdu-5976 Detachment 解题报告(乘法逆元、贪心?)
  18. 牧牛区块链培训,区块链对社会生产的五大好处
  19. 怎么选择合适的PLM系统
  20. 超市收银系统服务器,超市收银系统

热门文章

  1. mysql安装mac 压缩包_MySQL8.0安装详解(图文版)
  2. 【Elasticsearch】官方Elasticsearch Java客户端的状态
  3. 【Elasticsearch】所有可用 Qbox 插件的概述:第二部分
  4. 【clickhouse】clickhouse 的 数据类型
  5. 【LogStash】LogStash 配置后无法启动的问题
  6. 【MySQL】MySQL 如何查看sql语句执行时间和效率
  7. 95-120-042-源码-Cluster-SessionClusterEntrypoint
  8. 【Flink】Flink的窗口触发器 PurgingTrigger
  9. 【aviator】aviator 报错 Syntax error:Unexpect token 'OR' Parsing expression
  10. Spring : AutowireCapableBeanFactory自动装配能力