文档操作
执行新增方法
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESProductDaoTest {
@Autowired
private ProductDao productDao;
@Test
public void save(){
Product product = new Product();
product.setId(1L);
product.setTitle("华为手机");
product.setCategory("手机");
product.setPrice(2999.0);
product.setImages("http://www.atguigu/hw.jpg");
productDao.save(product);
}
}
执行上面的测试方法. 然后进行查询 get请求 http://127.0.0.1:9200/product/_doc/1 响应如下: 代表成功插入了数据
{
"_index": "product",
"_type": "_doc",
"_id": "1",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"found": true,
"_source": {
"_class": "com.thc.es.Product",
"id": 1,
"title": "华为手机",
"category": "手机",
"price": 2999.0,
"images": "http://www.atguigu/hw.jpg"
}
}
修改数据
@Test
public void update(){
Product product = new Product();
product.setId(1L);
product.setTitle("小米 2 手机");
product.setCategory("手机");
product.setPrice(9999.0);
product.setImages("http://www.atguigu/xm.jpg");
productDao.save(product);
}
根据id查询数据
@Test
public void findById(){
Product product = productDao.findById(1L).get();
System.out.println(product);
}
查询所有数据
@Test
public void findAll(){
Iterable<Product> products = productDao.findAll();
for (Product product : products) {
System.out.println(product);
}
}
删除数据
@Test
public void delete(){
Product product = new Product();
product.setId(1L);
productDao.delete(product);
}
批量新增数据
@Test
public void saveAll(){
List<Product> productList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Product product = new Product();
product.setId(Long.valueOf(i));
product.setTitle("["+i+"]小米手机");
product.setCategory("手机");
product.setPrice(1999.0+i);
product.setImages("http://www.atguigu/xm.jpg");
productList.add(product);
}
productDao.saveAll(productList);
}
分页查询数据
@Test
public void findByPageable(){
Sort sort = Sort.by(Sort.Direction.DESC,"id");
int currentPage=0;
int pageSize = 5;
PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
Page<Product> productPage = productDao.findAll(pageRequest);
for (Product Product : productPage.getContent()) {
System.out.println(Product);
}
}
|