org.springframework.data
spring-data-solr
1.5.5.RELEASE
org.springframework
spring-test
4.2.4.RELEASE
junit
junit
4.9
如果属性与配置文件定义的域名称不一致,需要在注解中指定域名称。
@Field
private Long id;
@Field("item_title")
private String title;
@Field("item_price")
private BigDecimal price;
@Field("item_image")
private String image;
@Field("item_goodsid")
private Long goodsId;
@Field("item_category")
private String category;
@Field("item_brand")
private String brand;
@Field("item_seller")
private String seller; .......
get set 方法.......................
@RunWith(SpringJUnit4ClassRunner.class) //使用JUnit4
@ContextConfiguration(locations="classpath:applicationContext-solr.xml") //扫加载配置文件
public class TestTemplate {
@Autowired
private SolrTemplate solrTemplate;
Test
@Text
//添加
public void testAdd(){
TbItem item=new TbItem();
item.setId(1L);
item.setBrand("华为");
item.setCategory("手机");
item.setGoodsId(1L);
item.setSeller("华为2号专卖店");
item.setTitle("华为Mate9");
item.setPrice(new BigDecimal(2000));
solrTemplate.saveBean(item);
solrTemplate.commit();
}
}
@ Test
public void testFindOne(){
TbItem item = solrTemplate.getById(1, TbItem.class);
System.out.println(item.getTitle());
}
@Test
public void testDelete(){
solrTemplate.deleteById("1");
solrTemplate.commit();
}
首先循环插入 100 条测试数据
@Test
public void testAddList(){
List list=new ArrayList();
for(int i=0;i<100;i++){ TbItem item=new TbItem();
item.setId(i+1L);
item.setBrand("华为");
item.setCategory("手机");
item.setGoodsId(1L);
item.setSeller("华为2号专卖店");
item.setTitle("华为Mate"+i);
item.setPrice(new BigDecimal(2000+i));
list.add(item);
}
solr Template.saveBeans(list);
solrTemplate.commit();
}
@Test
testPageQuery
public void (){
Query query=new SimpleQuery("*:*");
query.setOffset(20);//开始索引(默认0)
query.setRows(20);//每页记录数(默认10)
ScoredPage page = solrTemplate.queryForPage(query, TbItem.class);
System.out.println("总记录数:"+page.getTotalElements()); List list = page.getContent();
showList(list);
}
//显示记录数据
private void showList(List list){
item
for(TbItem :list){
System.out.println(item.getTitle() +item.getPrice());
}
}
Criteria 用于对条件的封装:
@Test
public void testPageQueryMutil(){
Query query=new SimpleQuery("*:*");
Criteria criteria=new Criteria("item_title").contains("2");
criteria=criteria.and("item_title").contains("5");
query.addCriteria(criteria);
//query.setOffset(20);//开始索引(默认0)
//query.setRows(20);//每页记录数(默认10)
ScoredPage page = solrTemplate.queryForPage(query, TbItem.class);
list
System.out.println("总记录数:"+page.getTotalElements()); List = page.getContent();
list
showList( );
}
@Test
public void testDeleteAll(){ Query query=new SimpleQuery("*:*");
solrTemplate.delete(query);
solrTemplate.commit();
}