跳到主要内容

集成数据访问层 SpringData

Spring Data 结合 Nasu Elasticsearch Serverless,我们不需要部署数据库或ES服务,即可为项目快速搭建一个存储库数据访问层(DAO),同时集成强劲的云端搜索引擎功能。

spring-data

Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷,并支持map-reduce框架和云计算数据服务。 Spring Data可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能。

快速开始

前置条件提示

请确保你的机器IP已在应用白名单内

示例项目
# 下载示例代码
git clone git@github.com:nasuyun/example-springboot-data.git

cd example-springboot-data/

# 替换成你的用户名及密码
vi ./src/main/resources/application.properties

# 启动
mvn clean package -DskipTests && java -jar ./target/springboot-data-0.0.1.jar

写入数据

curl -XPOST -H 'Content-Type:application/json' http://localhost:8080/posts -d '{"title" :"today","content":"hello world!" }'

获取数据

curl -XGET http://localhost:8080/posts

返回

[
{
"id": "5jMziYYBF92yhScr-Hl5",
"title": "Post one",
"content": "content of Post one"
},
{
"id": "XDkziYYB2Uy2itUn-KDp",
"title": "Post two",
"content": "content of Post two"
},
{
"id": "5zM0iYYBF92yhScrNnn0",
"title": "some content",
"content": null
},
{
"id": "E4g0iYYB_Kf6ohd7qJdy",
"title": "today",
"content": "hello world!"
}
]

示例项目讲解

https://github.com/nasuyun/example-springboot-data

环境版本一览

环境版本说明
jdk17.0.3Java环境
maven3.6.3依赖编译环境
spring-boot3.0.2spring boot
nasu elasticsearch serverlessv7云端ES
实体类
@Document(indexName = "posts")
@Data
@ToString
@Builder
class Post {
@Id
private String id;

@Field(store = true, type = FieldType.Text, fielddata = true)
private String title;

@Field(store = true, type = FieldType.Text, fielddata = true)
private String content;
}

操作类
interface PostRepository extends ReactiveElasticsearchRepository<Post, String> {
}
使用操作类
private final PostRepository posts;

public PostController(PostRepository posts) {
this.posts = posts;
}

// 查询数据
@GetMapping("")
public Flux<Post> all() {
return this.posts.findAll();
}

// 写入数据
@PostMapping("")
public Mono<Post> create(@RequestBody Post post) {
return this.posts.save(post);
}