新增和更新
Repository文檔操作
Spring Data 的強大之處,就在于你不用寫任何DAO處理,自動根據方法名或類的信息進行CRUD操作。只要你定義一個接口,然后繼承Repository提供的一些子接口,就能具備各種基本的CRUD功能。
我們只需要定義接口,然后繼承它就OK了。
public interface ItemRepository extends ElasticsearchRepository<Item,Long> { }來看下Repository的繼承關系:
我們看到有一個ElasticsearchRepository接口:
新增文檔
@Autowired private ItemRepository itemRepository;@Test public void index() {Item item = new Item(1L, "小米手機7", " 手機","小米", 3499.00, "http://image.learn.com/13123.jpg");itemRepository.save(item); }去頁面查詢看看:
GET /item/_search結果:
{"took": 14,"timed_out": false,"_shards": {"total": 1,"successful": 1,"skipped": 0,"failed": 0},"hits": {"total": 1,"max_score": 1,"hits": [{"_index": "item","_type": "docs","_id": "1","_score": 1,"_source": {"id": 1,"title": "小米手機7","category": " 手機","brand": "小米","price": 3499,"images": "http://image.learn.com/13123.jpg"}}]} }批量新增
代碼:
@Test public void indexList() {List<Item> list = new ArrayList<>();list.add(new Item(2L, "堅果手機R1", " 手機", "錘子", 3699.00, "http://image.learn.com/123.jpg"));list.add(new Item(3L, "華為META10", " 手機", "華為", 4499.00, "http://image.learn.com/3.jpg"));// 接收對象集合,實現批量新增itemRepository.saveAll(list); }再次去頁面查詢:
{"took": 5,"timed_out": false,"_shards": {"total": 1,"successful": 1,"skipped": 0,"failed": 0},"hits": {"total": 3,"max_score": 1,"hits": [{"_index": "item","_type": "docs","_id": "2","_score": 1,"_source": {"id": 2,"title": "堅果手機R1","category": " 手機","brand": "錘子","price": 3699,"images": "http://image.learn.com/13123.jpg"}},{"_index": "item","_type": "docs","_id": "3","_score": 1,"_source": {"id": 3,"title": "華為META10","category": " 手機","brand": "華為","price": 4499,"images": "http://image.learn.com/13123.jpg"}},{"_index": "item","_type": "docs","_id": "1","_score": 1,"_source": {"id": 1,"title": "小米手機7","category": " 手機","brand": "小米","price": 3499,"images": "http://image.learn.com/13123.jpg"}}]} }修改文檔
修改和新增是同一個接口,區分的依據就是id,這一點跟我們在頁面發起PUT請求是類似的。
總結