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

这篇具有很好参考价值的文章主要介绍了Springboot --- 整合spring-data-jpa和spring-data-elasticsearch。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

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

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

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

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

Springboot --- 整合spring-data-jpa和spring-data-elasticsearch文章来源地址https://www.toymoban.com/news/detail-424522.html

  • 正确写法如下
    注意:启动类上面还有两个注解
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 项目结构

  • 项目结构
    Springboot --- 整合spring-data-jpa和spring-data-elasticsearch

到了这里,关于Springboot --- 整合spring-data-jpa和spring-data-elasticsearch的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot原理分析 | Spring Data整合:JDBC、Druid、Mybatis

    💗wei_shuo的个人主页 💫wei_shuo的学习社区 🌐Hello World ! Spring Data是一个用于简化数据库访问和操作的开源框架,为开发人员提供了一种通用的方式来处理不同类型的数据存储,例如关系型数据库(如MySQL、PostgreSQL、Oracle)和非关系型数据库(如MongoDB、Cassandra、Redis)等。

    2024年02月12日
    浏览(39)
  • Spring Data JPA 学习笔记

    Spring Data JPA: Spring Data JPA 的技术特点: @Entity 标注是一个实体类,实体类中的每一个属性都对应表中的一列。 @Table(name = “User”) 这个注解用于指定实体类对应的数据库表名。(但首字母会小写) @Data:这个注解是Lombok库提供的,用于自动生成实体类的getter和setter方法、构造函

    2024年04月09日
    浏览(43)
  • Spring Data JPA 快速上手

    JPA的全称是Java Persisitence API,即JAVA持久化API,是sum公司退出的一套基于ORM的规范,内部是由一些列的接口和抽象类构成。JPA通过JDK5.0注解描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。 Spring Data的优势:可以操作多种数据库,关系型数据库,非关系

    2024年04月23日
    浏览(23)
  • Spring data JPA常用命令

    Spring Data JPA是Spring框架的一部分,它提供了一个简化的方式来与关系型数据库进行交互。JPA代表Java持久化API,它是Java EE规范中定义的一种对象关系映射(ORM)标准。Spring Data JPA在JPA的基础上提供了更高级的抽象,使得开发人员能够更轻松地进行数据库操作。 使用Spring Data

    2024年02月15日
    浏览(42)
  • SpringBoot整合Spring Data Elasticsearch,写给互联网大厂员工的真心话

    @RunWith(SpringRunner.class) @SpringBootTest(classes = ItcastElasticsearchApplication.class) public class IndexTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; //注入ElasticsearchTemplate类 @Test public void testCreate(){ // 创建索引,会根据Item类的@Document注解信息来创建 elasticsearchTemplate.createIndex(Item.class)

    2024年04月14日
    浏览(57)
  • Spring Data JPA的@Entity注解

     rulesCouponTypeConverter.java  entity/CouponTemplate.java Spring JPA 包的标准注解,对数据库字段进行了映射,我挑几个关键注解说道一下。 1、Entity:声明了“数据库实体”对象,它是数据库 Table 在程序中的映射对象; 2、Table:指定了 CouponTemplate 对应的数据库表的名称; 3、ID/Generat

    2024年02月11日
    浏览(40)
  • Spring Boot 篇四: Spring Data JPA使用SQL Server

    本篇介绍篇一至篇三中用到的JPA链接SQL Server的具体情况以及实战过程中可能遇到的问题。 具体的下载和安装教程,请参阅微软SQL Server官网; SQL Server Express 是免费的,并且配套的SQL Server Management Studio也是可以用的。 呃,当然,使用Docker来运行SQL Server是另外一条路径。具体

    2024年02月05日
    浏览(84)
  • Spring Data JPA之自动创建数据库表

    由于在项目中使用到了Spring Data JPA(Java Persistent API)进行项目开发,并且自己对JPA比较感兴趣想进行学习和了解。首先学习和了解的是JPA自动创建数据库表,通过JPA能够让软件工程师们不用再去手动创建数据表,能够减轻软件工程师们的工作量。 通过本篇博客可以实现使用

    2024年02月05日
    浏览(39)
  • 如何使用Spring Data JPA简化MySQL数据访问

    本篇文章是 “一起学习mysql” 系列的第五篇文章,本篇文章我们学习一下Spring Data JPA的使用,在开始学习器,我们先来了解一下什么是JPA。 JPA的全称是Java Persistence API,是J2EE中的一条规范,它标准化了数据持久化API。在上一篇文章中,我们了解了如何使用MyBatis进行MySQL数据

    2024年02月15日
    浏览(53)
  • 【Springboot系列】SpringBoot整合Jpa

    前言: Spring Boot是一种快速开发框架,它简化了Java应用程序的开发过程。而Jpa(Java Persistence API)是Java持久化规范的一种实现,它提供了一种方便的方式来访问和操作数据库。将Spring Boot与Jpa整合可以更加方便地进行数据库操作,提高开发效率。本文将介绍如何使用Spring Bo

    2024年02月05日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包