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

Springboot --- 整合spring-data-jpa和spring-data-elasticsearch,第1张

Springboot --- 整合spring-data-jpa和spring-data-elasticsearch
    • 1.依赖
    • 2.配置文件
    • 3.代码部分

整理不易,不喜勿喷。谢谢

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.
Sprignboot — 详解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.代码部分

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(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;
    private String username;
    private String password;
    private int age;
}

2.Repository

像下面这样写,肯定是不行的
比如:JpaRepository有save()方法,ElasticsearchRepository也有save()方法,它如何执行,启动就会报错

正确写法如下:
	注意:启动类上面还有两个注解
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.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();
    }
}

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;
    }

}

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);
    }

}

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);
        }
    }
}

7.项目结构

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/719353.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存