简单重构了一下 底层: 只有重构where查询。。。
其实前一断时间已经完成了.. 只是一个练手之作
个人推荐 一些固定的查询语句还是使用JQL直接查询 效果最佳
而一些需要你动态拼装字符的可以使用Criteria查询 这样子效率更高
追加两个类用来存放值
public class QueryObject { private String queryName; private Object queryValue; public QueryObject(String queryName, Object queryValue) { super(); this.queryName = queryName; this.queryValue = queryValue; } public String getQueryName() { return queryName; } public void setQueryName(String queryName) { this.queryName = queryName; } public Object getQueryValue() { return queryValue; } public void setQueryValue(Object queryValue) { this.queryValue = queryValue; } }
public enum QueryType { GREATERTHAN{public String getName(){return "大于";}}, LESSTHAN{public String getName(){return "小于";}}, EQUAL{public String getName(){return "等于";}}; abstract String getName(); }
DAO层 追加接口
public QueryResult<T> getScrollData(HashMap<QueryObject,QueryType> where); // 此处泛型必须为此顺序,否则存入是以key作为存放的索引,后者将会把前者覆盖
@Override public QueryResult<T> getScrollData(HashMap<QueryObject,QueryType> where) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<T> cq = cb.createQuery(entityClass); Root<T> root = cq.from(entityClass); cq.where(cb.and(buildQueryWhere(cb, root, where).toArray(new Predicate[0]))); TypedQuery<T> query = em.createQuery(cq); QueryResult<T> qr = new QueryResult<T>(); qr.setResultlist(query.getResultList()); return qr; }
构建where 语句方法:
protected static <T> List< Predicate> buildQueryWhere(CriteriaBuilder cb,Root<T> root,HashMap<QueryObject,QueryType> where){ List< Predicate> predicates = new ArrayList< Predicate>(); for(Map.Entry<QueryObject,QueryType> entry : where.entrySet()){ QueryType qt = entry.getValue(); QueryObject qo = entry.getKey(); switch (qt) { case EQUAL: predicates.add(cb.equal(root.get(qo.getQueryName()), qo.getQueryValue())); break; case GREATERTHAN: predicates.add(cb.gt(root.<Integer>get(qo.getQueryName()),Integer.parseInt(qo.getQueryValue().toString()))); break; case LESSTHAN: predicates.add(cb.lt(root.<Integer>get(qo.getQueryName()),Integer.parseInt(qo.getQueryValue().toString()))); break; default: System.out.println("还没定义呢。。。 "); } } return predicates; }
测试类。。。
@Test public void testGetScrollData(){ HashMap<QueryObject,QueryType > where = new HashMap<QueryObject,QueryType >(); where.put(new QueryObject("gender",Gender.MAN) , QueryType.EQUAL); where.put(new QueryObject("password", "123123") , QueryType.EQUAL ); QueryResult<Buyer> qr = buyerService.getScrollData(where); for(Buyer buyer : qr.getResultlist()){ System.out.println(buyer.getUsername() + " " + buyer.getRegTime() + " " + buyer.getGender()); } }
Hibernate: select buyer0_.username as username1_, buyer0_.contact_id as contact8_1_, buyer0_.email as email1_,
buyer0_.gender as gender1_, buyer0_.password as password1_, buyer0_.realname as realname1_, buyer0_.regTime
as regTime1_, buyer0_.visible as visible1_ from Buyer buyer0_ where buyer0_.password=? and buyer0_.gender=?
liming 2012-02-16 21:50:31.0 MAN
tiantian 2012-02-16 22:07:51.0 MAN