首页 > 代码库 > 实现按条件查询

实现按条件查询

第一步:

定义接口:

public interface ICommonDao<T> {

 List<T> findCollectionByConditionNoPage(String codition,Object[] params, Map<String, String> orderby);


}


第二步:
实现接口的类:



Class entityClass = TUtils.getTClass(this.getClass());

public class TUtils {

	/**泛型转换,目的获取子类传递父类的真实类型。也就是T所相应的类型*/
	public static Class getTClass(Class entity) {
		ParameterizedType type = (ParameterizedType)entity.getGenericSuperclass();
		Class entityClass = (Class) type.getActualTypeArguments()[0];
		return entityClass;
	}

}





/**指定查询条件查询相应的结果,返回List(不分页)*/
	/**
	 * FROM ElecText o WHERE 1=1        #Dao层
		AND o.textName LIKE ‘%张%‘	#Service层
		AND o.textRemark LIKE ‘%张%‘    #Service层
		ORDER BY o.textDate ASC,o.textName DESC  #Service层
	 */
	public List<T> findCollectionByConditionNoPage(String condition,
			final Object[] params, Map<String, String> orderby) {
		//定义hql语句
		String hql = "FROM "+entityClass.getSimpleName()+" o WHERE 1=1";
		//定义排序语句
		String orderbyHql = this.orderbyHql(orderby);
		//定义终于的语句
		final String finalHql = hql + condition + orderbyHql;
		//运行语句一
		//List<T> list = this.getHibernateTemplate().find(finalHql, params);
		//运行语句二
//		SessionFactory sf = this.getHibernateTemplate().getSessionFactory();
//		Session s = sf.getCurrentSession();
//		Query query = s.createQuery(finalHql);
//		List<T> list = query.list();
		//运行语句三
		List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(finalHql);
				if(params!=null && params.length>0){
					for(int i=0;i<params.length;i++){
						query.setParameter(i, params[i]);
					}
				}
				return query.list();
			}
			
		});
		return list;
	}

	/**组织排序的语句*/
	/*ORDER BY o.textDate ASC,o.textName DESC*/
	private String orderbyHql(Map<String, String> orderby) {
		StringBuffer buffer = new StringBuffer("");
		if(orderby!=null && orderby.size()>0){
			buffer.append(" order by ");
			for(Map.Entry<String, String> map:orderby.entrySet()){
				buffer.append(map.getKey()+" "+map.getValue()+",");
			}
			//删除最后一个逗号
			buffer.deleteCharAt(buffer.length()-1);
		}
		return buffer.toString();
	}


以下是依据不同的业务来编写不同的代码。


第三步:

service接口:

public interface IElecTextService {
	public static final String SERVICE_NAME = "com.itheima.elec.service.impl.ElecTextServiceImpl";
	
	List<ElecText> findCollectionByConditionNoPage(ElecText elecText);
}


第四步:

service实现

/**指定查询条件查询相应的结果,返回List*/
	/**
	 * FROM ElecText o WHERE 1=1        #Dao层
		AND o.textName LIKE ‘%张%‘	#Service层
		AND o.textRemark LIKE ‘%张%‘    #Service层
		ORDER BY o.textDate ASC,o.textName DESC  #Service层
	 */
	public List<ElecText> findCollectionByConditionNoPage(ElecText elecText) {
		//查询条件
		String condition = "";
		List<Object> paramsList = new ArrayList<Object>();
		//推断是否加入查询条件
		if(StringUtils.isNotBlank(elecText.getTextName())){
			condition += " and o.textName like ?";
			paramsList.add("%"+elecText.getTextName()+"%");
		}
		if(StringUtils.isNotBlank(elecText.getTextRemark())){
			condition += " and o.textRemark like ?";
			paramsList.add("%"+elecText.getTextRemark()+"%");
		}
		Object [] params = paramsList.toArray();
		//排序语句(hql语句和sql语句的排序是有顺序的
		Map<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("o.textDate", "asc");
		orderby.put("o.textName", "desc");
		//查询
		List<ElecText> list = elecTextDao.findCollectionByConditionNoPage(condition,params,orderby);
		return list;
	}


第五步:

/**模拟Action,调用Service,指定查询条件查询相应的结果。返回List*/
	@Test
	public void findCollectionByConditionNoPage(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
		IElecTextService elecTextService = (IElecTextService) ac.getBean(IElecTextService.SERVICE_NAME);
		
		ElecText elecText = new ElecText();
//		elecText.setTextName("张");
//		elecText.setTextRemark("张");
		
		List<ElecText> list = elecTextService.findCollectionByConditionNoPage(elecText);
		if(list!=null && list.size()>0){
			for(ElecText elecText2:list){
				System.out.println(elecText2.getTextName()+"    "+elecText2.getTextDate()+"     "+elecText2.getTextRemark());
			}
		}
	}


真正的action:

package com.itheima.elec.web.action;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.itheima.elec.domain.ElecSystemDDL;
import com.itheima.elec.service.IElecSystemDDLService;


@SuppressWarnings("serial")
@Controller("elecSystemDDLAction")
@Scope(value=http://www.mamicode.com/"prototype")>
总结:依据什么样的条件查询,是在service层完毕的,把全部的条件组织好后,给dao层,dao层再拼接SQL或者hql语句,进行真正的查询。web层的action仅仅是传递參数,进行简单的调用service层的方法。




实现按条件查询