Spring Data整合
核心接口
a org.springframework.data.respository.Respository
b org.springframework.data.respository.CrudRespository
c org.springframework.data.respository.PagingAndSortingRespository //分页排序
d @org.springframework.data.respository.NoRespositoryBean
spring data 工程
是一个 用于简化 数据库访问,并支持云服务的开源框架,旨在统一个简化对各类型持久化存储,而不拘泥于是关系型数据库还是NoSQL 数据存储
springBoot 1.5.14
Elasticsearch 2.4.6 (spring data 默认只支持 2.x 版本)
第一步 激活 Elasticsearch |
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@SpringBootApplication @EnableElasticsearchRepositories public class SpringBootLesson9Application {
public static void main(String[] args) { SpringApplication.run(SpringBootLesson9Application.class, args); } } |
配置 elasticsearch |
spring.data.elasticsearch.cluster-name=elasticsearch # 多个节点用逗号隔开 spring.data.elasticsearch.cluster-nodes=192.168.255.128:9300 |
编写实体类 |
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
@Document(indexName = "book",type = "it") public class User implements Serializable{ private String id; private String name;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; } } |
编写 repository 接口 |
import cn.shendu.springbootlesson9.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository; import org.springframework.stereotype.Component; import org.springframework.util.Assert;
@Component public interface UserElasticsearchRepository extends ElasticsearchRepository<User,String> { } |
编写 controller |
import cn.shendu.springbootlesson9.domain.User; import cn.shendu.springbootlesson9.repository.UserElasticsearchRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@RestController public class UserController {
@Autowired private UserElasticsearchRepository userElasticsearchRepository;
@RequestMapping("/get/user") public User getUser(@RequestBody User user){ User u = userElasticsearchRepository.findOne(user.getId());
return u; }
@RequestMapping("/add/user") public String add(){ User user = new User(); user.setId("1"); user.setName("shendu"); userElasticsearchRepository.save(user); return "success"; }
} |
测试结果
参考
小马哥 spring-boot 教程