ehcache属性查询问题,如果单单往ehcache testcache中添加User对象,在查询的时候不会出问题,但是如果再往testcache添加一个对象,那就会出现查询错误
package cache;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 2098760172778119467L;
private Integer id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String toString() {
return this.id + ":" + this.name;
}
}
/**
*
* @author hange
*/
public class CacheClass {
public String name;
}
package cache;
import java.io.Serializable;
import java.util.List;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.MemoryUnit;
import net.sf.ehcache.config.SearchAttribute;
import net.sf.ehcache.config.Searchable;
import net.sf.ehcache.search.Attribute;
import net.sf.ehcache.search.Query;
import net.sf.ehcache.search.Result;
import net.sf.ehcache.search.Results;
/**
*
* @author hange
*/
public class EhcacheTest {
public static void main(String[] args){
testEhcacheLike();
}
public static void testEhcacheLike(){
net.sf.ehcache.CacheManager manager = net.sf.ehcache.CacheManager.newInstance();
CacheConfiguration cacheConfig = new CacheConfiguration();
//定义属性查询
cacheConfig.name("testCache").maxBytesLocalHeap(100, MemoryUnit.MEGABYTES);
//新建一个Searchable对象
Searchable searchable = new Searchable();
//给Cache配置Searchable对象,表明该Cache是一个可查询的Cache
cacheConfig.searchable(searchable);
//新建一个查询属性
SearchAttribute searchAttribute = new SearchAttribute();
//指定查询属性的名称和属性提取器的类名
searchAttribute.name("name");
//Searchalbe对象添加查询属性
searchable.addSearchAttribute(searchAttribute);
//使用CacheConfig创建Cache对象
Cache cache = new Cache(cacheConfig);
//把Cache对象纳入CacheManager的管理中
manager.addCache(cache);
Cache testCache = manager.getCache("testCache");
//模糊查询测试
User u = null;
for(int i = 0; i < 100; i++){
u = new User(i, "wanjunjun"+i);
testCache.put(new Element(u.getId(), u));
}
CacheClass test cacaheObj = new CacheClass();
cacaheObj .name = "xxx";
testCache.put ( new Element(1001, cacaheObj ) ); //加上这个就会出现查询错误
//获取名称为name的可查询属性Attribute对象
Attribute<String> name = testCache.getSearchAttribute("name");
//创建一个用于查询的Query对象
Query query = testCache.createQuery();
query.includeKeys();
query.includeValues();
//给当前query添加一个筛选条件——可查询属性name的值等于wanjunjun
query.addCriteria(name.ilike("wanjunjun?"));
//执行查询操作,返回查询结果Results
Results results = query.execute();
manager.shutdown();
}
}