Spring Boot数据访问

  • Post author:
  • Post category:其他




Spring Boot数据访问概述

Spring Data是Spring提供一个用于简化数据库访问,支持云服务的开源框架,包含了大量关系型数据库的数据访问解决方案。

SpringData提供了多种类型的数据库支持,SpringBoot对SPringData的值池的数据库进行整合管理,提供了各种依赖启动器。

Spring Boot提供的数据库依赖启动器

名称 描述
spring-boot-starter-data-jpa Spring DataJPA与Hibernate的启动器
spring-boot-starter-data-mongodb MongoDB和Spring Data MongoDB的启动器
spring-boot-starter-data-neo4j Neo4j图数据库和Spring Data Neo4j的启动器
spring-boot-starter-data-redis Redis键值数据存储与Spring Redis和Jedis客户端的启动器



Spring Boot整合MyBatis



基础环境搭建



数据准备

在MySql中创建一个名为springbootdata的数据库,在该数据库中创建两个表,t_comment和t_artcile并预先插入几条数据。

create database springbootdata;
use springbootdata;
drop table if exists `t_article`;
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基础入门','从入门到精通讲解...');
drop table if exists `t_comment`;
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','123','tom1','1');
insert into `t_comment` values ('2','123','tom2','1');
insert into `t_comment` values ('3','123','tom3','1');
insert into `t_comment` values ('4','123','tom4','1');
insert into `t_comment` values ('5','123','tom5','2');



创建项目,引入相应启动器

(1)创建SpringBoot项目,创建一个名为shuju的Spring Boot项目,在Dependendcise依赖中选择SQL模块中的MySQL和MyBatis依赖。

(2)创建一个名为com.itheima.damain的包,编写数据库对应的实体类Comment和Article。

Comment

package com.itheima.domain;

public class Comment {
    private Integer id;
    private String content;
    private String author;
    private Integer aId;

    public Integer getId() {
        return id;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getaId() {
        return aId;
    }

    public void setaId(Integer aId) {
        this.aId = aId;
    }

    @Override
    public String toString() {
        return "Comment{" +
                "id=" + id +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                ", aId=" + aId +
                '}';
    }
}

Article

package com.itheima.domain;

import java.util.List;

public class Article {
    private Integer id;
    private String title;
    private String content;
    private List<Comment> commentList;

    public Integer getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public List<Comment> getCommentList() {
        return commentList;
    }

    public void setCommentList(List<Comment> commentList) {
        this.commentList = commentList;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", commentList=" + commentList +
                '}';
    }
}



编写配置文件

(1)在application.properties配置文件中进行数据库连接配置,在配置文件中编写对应的MySQL数据库连接配置

spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimeZone=UTC
spring.datasource.username=root
spring.datasource.password=123456

(2)数据源类型选择,在pom.xml文件中天剑Druid数据源的依赖

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

(3)在application.properties修改第三方Druid的运行参数

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=20
spring.datasource.minIdle=10
spring.datasource.maxActive=100

(4)在com,ithima.config下创建一个自定义配置类对Druid数据源属性值进行注入

package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDruid(){
        return new DruidDataSource();
    }
}



使用注解的方式整合MyBatis

相对于Spring 和MyBatis的整合Spring Boot和MyBatis的整合会使项目开发更贱渐变同时还支持XML和注解两种配置方式

使用注解的方式整合Spring Boot和MyBatis整合

示例

(1)在com.itheima.mapper下创建Mapper接口文件

package com.itheima.mapper;
import com.itheima.domain.Comment;
import org.apache.ibatis.annotations.*;
@Mapper
public interface CommentMapper {
    @Select("select * from t_comment where id=#{id}")
    public Comment findByid(Integer id);
    @Insert("INSERT into t_comment(comment,author,a_id)"+"values (#{content},#{authod},#{aId}")
    public int inssertComment(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);
}

(2)编写单元测试接口方法测试在测试类中引入CommentMapper接口,并对接口方法进行测试

package com.itheima;
import org.junit.runner.RunWith;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.itheima.domain.*;
import com.itheima.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
@RunWith(SpringRunner.class)
@SpringBootTest
 public class ShujuApplicationTests {
    @Test
    public void contextLoads() {
    }
    @Autowired
    private CommentMapper commentMapper;
    @Test
    public  void selectComment(){
        Comment comment=commentMapper.findByid(1);
        System.out.println(comment);
    }

}

(3)运行测试类

在这里插入图片描述

aId属性为null,说明没有映射成功这是因为编写的实体类Comment中使用了驼峰命名方法将t_comment表中的a_id字段涉及乘客aid属性无法正确映射查询结果,我们需要在全局配置文件中添加一句

mybatis.configuration.map-underscore-to-camel-case=true

在这里插入图片描述



使用配置文件的方式整合MyBatis

Spring Boot与MyBatis整合使用时,不仅支持注解方式,还支持XML配置文件。

示例:

(1)创建Mapper接口文件,com.itheima.mapper包下创建一个数据表t_articleMapper

package com.itheima.mapper;

import com.itheima.domain.Article;
import org.apache.ibatis.annotations.Mapper;
import  org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface ArticleMapper {
    public Article selectArtile(Integer id);
    public int updateArticle(Article article);
}

(2)创建XML映射文件,在resource目录下创建一个mapper包,创建ArticleMapper.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.itheima.mapper.ArticleMapper">
    <select id="selectArtile" resultMap="articleWithComment">
        select a.*,c.id c_id,c.content c_content,c.author
        from t_article a,t_comment c
        where 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"/>
        <collection property="commentList" ofType="Comment">
            <id property="id" column="c_id"/>
            <result property="content" column="c_content"/>
            <result property="author" column="author"/>
        </collection>
    </resultMap>
    <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>

    </update>
</mapper>

(3)配置XML映射文件路径,在全局变量中编写XML映射文件

mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.itheima.domain

(4)编写单元测试进行接口方法测试,打开项目的测试类ShujuApplicationTests,在测试类中引入ArticleMapper接口,并对接口方法进行测试

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

在这里插入图片描述



Spring Boot整合JPA



Spring Data JPA介绍

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



编写ORM实体类

Spring Data JPA框架针对具有ORM关系的数据进行操作所以使用Spring Data JPA首先需要编写一个实体类和数据表进行映射,并且配置好映射关系

示例代码如下

在pom.xml文件下添加下列代码导入依赖。

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

然后在com.itheima.domain包下创建一个实体类

@Entity(name="t_comment")
public class Discuss
	@Id
	@GeneratedValue(startegy=GenerationType.IDENTITY)
	private Integer id;
	@Column(name="a_id")
	private Integer aId;
	//省略get和set方法

上述代码定义了一个Spring Data JPA实体类Discuss,并将该类与数据表t_comment进行映射,上述代码有许多注解:

(1)@Entity:标注要与数据库做映射的实体类,默认情况下数据表的名称就是首字母小写的类名,还可以使用name属性指定映射的类名。

(2)@Id:标注在类属性或者getter方法上,表示某一个属性对应表中的主键

(3)@GeneratedValue:与@Id注解标注在同一位置,用于表示属性对应主键的生成策略,可以省略。Spring Data JPA支持的主键生成策略有TABLE(使用一个特定的数据库表格来保存主键)、SEQUENCE(不支持主键自增脏的数据库主键生成策略)、IDENTITY(主键自增)、AUTO(JAP自主选择前面3种合适的策略,是默认选项)

(4)@Column:标注在属性上,当类属性和表字段名不同时,能够配合name属性表示类属性对应的表字段名



编写Repository接口

代码如下:

package com.itheima.mapper;

import com.itheima.domain.Discuss;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.awt.print.Pageable;
import java.util.List;

public interface Respository extends JpaRepository<Discuss,Integer> {
    public List<Discuss> findByAutorNotNull();
    @Query("SELECT c from t_comment c where c.aId=?1")
    public List<Discuss> getDiscussPage(Integer aid, Pageable pageable);
    @Query(value = "SELECT * FROM t_comment where a_Id=?1",nativeQuery=true)
    public List<Discuss> getDiscussPage2(Integer aid,Pageable pageable);
    @Transactional
    @Modifying
    @Query("DELETE t_comment c where c.id=?1")
    public int deleteDiscuss(Integer id);
}

上述代码些了许多的方法

(1)findByAutthorNotNull():该方法是一个基本的查询方法,上方没有任何注解属于JPA支持的方法名关键字查询方式。

(2)getDiscussPaged()方法该方法商法通过@Query注解引入一个SQL语句,用于通过文章分页ID查询Discuss评论信息

(3)getDiscussPaged2()方法:该方法的功能与getDiscussPaged()基本类似,区别是该方法上方的@Query注解将nativeQuery属性设置为true,用来编写原生SQL语句。

(4)updateDiscuss()方法和deleteDiscuss()方法:这两个方法同样使用@Query注解配置了对应的SQL语句,这两个方法分别对应数据的更新和删除操作。

需要注意的问题

(1)使用Spring Data JPA自定义的Repository接口必须继承XXRepository<T,ID>接口,其中T代表要操作的实体类,ID代表实体类主键数据类型。

1.Repository是Spring Data JPA提供的用于自定义Repository接口的顶级父接口,该接口没有声明任何方法

2.CrudRepository接口是Repository是继承的接口之一,包含了一些基本的CRUD方法。

3.PagingAndSortingRepository接口继承CrudRepository接口的同时,提供了分页和排序两个方法。

4.QueryByExampleExecutor接口时进行条件疯转查询的顶级父接口允许通过Example示例执行复杂条件查询。

JpaRepository接口同时继承了PagingAndSortingRepository接口和QueryByExample接口,并额外提供一些数据操作方法。自定义Repository接口文件时,通常会直接选择继承JpaRepository接口

(2)在使用Spring Data JPA进行数据操作是,可以有多种实现方式,主要方式如下:

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

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

Spring Data JPA中支持的方法名关键字即对应的SQL语句片段说明

关键字 方法名示例 对应的SQL片段
And findByLastnameAndFirstname where x.lastname=?1 and x.firstnaem=?2
Or findByFirstnamelsyLastnameOrFirstname where x.lastname=?1 or x.firstname=?2
Is,Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals where x.firstname=?1
Between findByStartDateBetween where x.startDate between?1and ?2
LessThan findByAgeLessThan where x.age<?1
LessThanEqual findByAgeLessThanEqual where x.age<=?1
GreaterThan findByAgeGreaterThan weher x.age>?1
GreaterThanEqual findByAgeGreaterThanEqual weher x.age>=?1
After findByStartDateAfter where x.startDate>?1
Before findByStartDateBefore where x startDate<?1
IsNull findByAgeisNull where x,age is null
IsNotNull,NotNull findByAge(Is)NotNull wherex.age not null
Like findByFirstnameLike where x.firstname like ?1
NotLike findByFirstnameNotLike where x.firstname not like ?1
StartWith findByFirstnameStartingWith where x.firstname.like ?1(绑定参数 %)
EndWith findByFirstnameEndingWith where x.firstname.like ?1(绑定参数 %)
Containing findByFirstnameContaining where x.firstname.like ?1(绑定参数 %)
OrderBy findBuAgeOrderByLastnameDesc where x.age=?1order by x.lastname desc
Not findByLastnameNot where x.lastname<>?1
In findByAgein(Collection< Age> ages) where x.age in?1
True findByActiveTrue() where x.active=true
false findByActiveFalse() where x.active=false
lgnoreCase findByFirstnamelgnoreCase where UPPER(x.firstname)=UPPER(?1)

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

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

(5)JPA叫支持使用Example示例进行复杂条件查询。

        //用example精确匹配查询条件
        Discuss discuss=new Discuss();
        discuss.setAuthor("123");
        Example<Discuss> example=Example.of(discuss);
        List<Discuss> list=repository.findAll(example);
        //用exampleMatcher模糊匹配查询条件
        Discuss discuss1=new Discuss();
        discuss.setAuthor("1");
        ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("author",startsWith());
        Example<Discuss> example1=Example.of(discuss,matcher);
        List<Discuss> list=repository.findAll(example);



使用Spring Boot整合JPA

(1)添加Soring DataJPA启动器,在项目pom.xml添加Spring DataJPA依赖启动器

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

(2)编写ORM实体类,编写一个叫Disscuss的实体类

package com.itheima.domain;
import javax.persistence.*;
@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;

    public Integer getId() {
        return id;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getaId() {
        return aId;
    }

    public void setaId(Integer aId) {
        this.aId = aId;
    }

    @Override
    public String toString() {
        return "Discuss{" +
                "id=" + id +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                ", aId=" + aId +
                '}';
    }
}

(3)编写Repository接口,创建一个com.itheima.repository包,创建一个用于对数据库表t_comment进行操作的Repository接口DiscussRepository

package com.itheima.mapper;

import com.itheima.domain.Discuss;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import java.util.List;

public interface DiscussRepository extends JpaRepository<Discuss,Integer> {
    public List<Discuss> findByAuthorNotNull();
    @Query("SELECT c from t_comment c where c.aId=?1")
    public List<Discuss> getDiscussPaged(Integer aid, Pageable pageable);
    @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)编写单元测试进行接口方法测试,用来修改后编写DiscussRepository接口对应的测试方法

package com.itheima;
import com.itheima.domain.Discuss;
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.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.*;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import com.itheima.mapper.DiscussRepository;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import java.util.List;
import java.util.Optional;

import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;

@RunWith(SpringRunner.class)
@SpringBootTest
public class JpaTests {
    @Autowired
    private DiscussRepository repository;
    //使用JpaRepository内部方法进行数据操作
    @Test
    public void selectComment(){
        Optional<Discuss> optional=repository.findById(1);
        if(optional.isPresent()){
            System.out.println(optional.get());
        }
    }
    @Test
    public void selectCommentByKeys(){
        List<Discuss> list=repository.findByAuthorNotNull();
        System.out.println(list);
    }
    @Test
    public void selectCommentPaged(){
        Pageable pageable= PageRequest.of(0,3);
        List<Discuss> allPaged = repository.getDiscussPaged(1,pageable);
        System.out.println(allPaged);
    }
    @Test
    public void selectCommentByExample(){
        Discuss discuss=new Discuss();
        discuss.setAuthor("张三");
        Example<Discuss> example=Example.of(discuss);
        List<Discuss> list=repository.findAll(example);
        System.out.println(list);

    }
    @Test
    public void selectCommentByExampleMatcher(){
        Discuss discuss=new Discuss();
        discuss.setAuthor("tom");
        ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("author",startsWith());
        Example<Discuss> example=Example.of(discuss,matcher);
        List<Discuss> list=repository.findAll(example);
        System.out.println(list);
    }


}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述



SpringBOOt整合Redis



Redis介绍

Redis是一个开源的,内存中的数据结构存储系统,可以用作数据库,缓存和纤细中间件,并提供多种语言的API。

Redis的优点:

(1)存取速度快。

(2)支持丰富的数据类型

(3)操作具有原子性

(4)提供多种功能



Redis下载安装

使用field关系型数据库必须先安装配置并开启Redis服务,Redis的下载地址

https://github.com/MicrosoftArchive/redis/releases



Redis服务开启与连接配置

完成Redis安装后启动Redis服务,并使用可视化客户端工具连接对应的Redis服务进行效果测试。

Redis可视化客户端下载地址:


Redis可视化客户端





https://gitcode.net/mirrors/quick123official/quick_redis_blog?utm_source=csdn_github_accelerator


Redis解压完成后

在这里插入图片描述

打开redis-server.xml有可能会闪退

在目录下创建一个start.bat

redis-server.exe redis.windows.conf

启动服务

在这里插入图片描述

安装第一个可视化工具需要配置环境

打开redis-desktop-manager-0.9.3.817.exe进入后

在这里插入图片描述

点击连接服务器

在这里插入图片描述

输入名字和验证密码

如果不知道用户名和密码,可以运行redis-cli.exe然后输入

config get requirepass

用来查看用户名和密码



使用Spring Boot整合Redis

(1)在pom.xml文件中输入

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

(2)编写实体类Person、Address和Family

Person

package com.itheima.domain;


import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;

import javax.persistence.Id;
import javax.persistence.Index;
import java.util.List;

@RedisHash("persons")
public class Person {
    @Id
    private String id;
    @Indexed
    private  String firstname;
    @Indexed
    private String lastname;
    private Address address;
    private List<Family> familyList;
    public String getId() {
        return id;
    }

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

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    Person(){}
    public Person(String firstname, String lastname){
        this.firstname=firstname;
        this.lastname=lastname;
    }

    public List<Family> getFamilyList() {
        return familyList;
    }

    public void setFamilyList(List<Family> familyList) {
        this.familyList = familyList;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", firstname='" + firstname + '\'' +
                ", lastname='" + lastname + '\'' +
                ", address=" + address +
                '}';
    }

}

Address

package com.itheima.domain;

import org.springframework.data.redis.core.index.Indexed;

public class Address {
        @Indexed
        private String city;
        @Indexed
        private String country;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
    Address(){}
    public Address(String city, String country){
        this.city=city;
        this.country=country;
    }
    @Override
    public String toString() {
        return "Address{" +
                "city='" + city + '\'' +
                ", country='" + country + '\'' +
                '}';
    }
}

Family

package com.itheima.domain;

import org.springframework.data.redis.core.index.Indexed;

public class Family {
    @Indexed
    private String type;
    @Indexed
    private String username;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    Family(){}
    public Family(String Type, String username1){
        this.username=username;
        this.type=type;
    }
    @Override
    public String toString() {
        return "Family{" +
                "type='" + type + '\'' +
                ", username='" + username + '\'' +
                '}';
    }
}

其中有几个注释

1.@RedisHash(“persons”)用于指定操作实体类对象在Redis数据库中的存储空间,此处表示针对Person实体类数据操作都存储在Redis数据库中名为persons的存储空间中。

2.@Id:用于标识实体类主键。在Redis数据库中会默认生成字符串形式的HashKey表示唯一的实体对象id,当然也可以在数据存储时手动指定id。

3.@indexed:用于标记对应属性在Redis数据库中生成二级索引。使用该注解后会在Redis数据库中生成属性对应的二级索引,索引名称就是属性名,可以方便地进行数据条件查询。

(3)编写Repository接口

PersonRepository.java

package com.itheima.repostiory;

import com.itheima.domain.Person;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

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

(4)Redis数据库连接配置,在项目的全局配置文件中添加Redis数据库连接配置

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=

(5)编写单元测试进行接口方法测试

package com.itheima;
import org.junit.runner.RunWith;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.itheima.domain.*;
import com.itheima.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
@RunWith(SpringRunner.class)
@SpringBootTest
 public class ShujuApplicationTests {
    @Test
    public void contextLoads() {
    }
    @Autowired
    private CommentMapper commentMapper;
    @Test
    public  void selectComment(){
        Comment comment=commentMapper.findByid(1);
        System.out.println(comment);
    }
    @Autowired
    private ArticleMapper articleMapper;
    @Test
    public void selectArticle(){
        Article article=articleMapper.selectArtile(1);
        System.out.println(article);
    }

}

在这里插入图片描述

在这里插入图片描述



版权声明:本文为qq_50834939原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。