Springboot --- 整合spring-data-jpa和spring-data-elasticsearch

在这里插入图片描述


在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

SpringBoot: 整合Ldap.
SpringBoot: 整合Spring Data JPA.
SpringBoot: 整合Elasticsearch.
SpringBoot: 整合spring-data-jpa和spring-data-elasticsearch.
SpringBoot: 整合thymeleaf.
SpringBoot: 注入第三方jar包.
SpringBoot: 整合Redis.
SpringBoot: 整合slf4j打印日志.
SpringBoot: 整合定时任务,自动执行方法.
SpringBoot: 配置多数据源,使用JdbcTemplate以及NamedParameterJdbcTemplate.
SpringBoot: 详解pom.xml中build和profile.
SpringBoot: 监控.
SpringBoot: 缓存Cache/Redis.
SpringBoot: 整合Zookeeper.
Git: 使用详解.


       本节重点就是jpa和es共用一个实体类

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.nolan</groupId>
    <artifactId>spring-data-es</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-data-es</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. 配置文件

server.port=8085

spring.data.elasticsearch.client.reactive.endpoints=http://localhost:9200
spring.data.elasticsearch.repositories.enabled=true


spring.datasource.one.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.one.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.one.jdbc-url=jdbc:oracle:thin:@//xxxxxx:1521/xxxx
spring.datasource.one.username=xxxx
spring.datasource.one.password=xxxx

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

3. 代码部分

3.1 Entity

各注解详细介绍:

  • @Data 就是set/get方法
  • @Entity jpa封装的实体类
  • @Table jpa对应数据库的表
  • @Document es封装的实体类
  • @Id 主键
  • @GeneratedValue 主键的类型
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

import javax.persistence.*;

@Data
@Entity
@Table(name = "USERS")
@Document(indexName = "spring.test",indexStoreType = "user")
public class User {

    @javax.persistence.Id
    @Id
    @GeneratedValue(xxxxx)
    @Column(name = "id")
    private int id;
    private String username;
    private String password;
    private int age;
}

3.2 Repository

  • 像下面这样写,肯定是不行的

在这里插入图片描述

  • 正确写法如下
    注意:启动类上面还有两个注解
import com.nolan.es.entity.User;
import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.Optional;

public interface UserEsRepository extends ElasticsearchRepository<User, Integer> {


    @Override
    @Highlight(fields = {
            @HighlightField(name = "username"),
            @HighlightField(name = "age")
    })
    Optional<User> findById(Integer integer);
}
import com.nolan.es.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

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

3.3 Config

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DBConfig {
    @Bean(name = "dsOne1")
    @Qualifier("dsOne1")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.one")
    public DataSource dsOne1(){
        return DataSourceBuilder.create().build();
    }
}

3.4 Service

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public boolean checkIndexExists(Class<?> cls ){
        boolean isExist = elasticsearchRestTemplate.indexOps(cls).exists();
        //获取索引名
        String indexName = cls.getAnnotation(Document.class).indexName();
        System.out.printf("index %s is %s\n", indexName, isExist ? "exist" : "not exist");
        return isExist;
    }

}

3.5 启动类

  • 这两个注解非常重要
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories("com.nolan.es.dao.jpa")
@EnableElasticsearchRepositories("com.nolan.es.dao.es")
public class SpringDataEsApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringDataEsApplication.class, args);
    }

}

3.6 Test

import com.nolan.es.dao.es.UserEsRepository;
import com.nolan.es.dao.jpa.UserJpaRepository;
import com.nolan.es.entity.User;
import com.nolan.es.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import java.util.Iterator;
import java.util.Optional;

@SpringBootTest
class SpringDataEsApplicationTests {

    @Autowired
    private UserEsRepository esRepository;
    @Autowired
    private UserJpaRepository jpaRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Test
    void contextLoads() {

        boolean result = userService.checkIndexExists(User.class);

        Iterable<User> all = jpaRepository.findAll();
        Iterator<User> userIterators = all.iterator();

        while (userIterators.hasNext()){
            User next = userIterators.next();
            esRepository.save(next);
            System.out.println(1);
        }
    }
}

3.7 项目结构

  • 项目结构
    在这里插入图片描述
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百世经纶『一页書』

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值