Hibernate的HQL中,通过参数名称和参数值 ,封装成Map。

 

在JavaBean中需要,返回一个Map集合的键值对形式。key->参数名,value->绑定查询的值。封装成Map 传入给后台.

代码如下:

package com.common.core.service;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UserSearchCriteria implements SearchCriteria {

	private static final long serialVersionUID = -2410746683028614279L;
	final static Log logger = LogFactory.getLog(UserSearchCriteria.class);

	private String userId;
	private String firstName;
	private String lastName;
	private String email;
	private String age;
	private String gender;
	private String status;

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}
	
	public void reset(){
		this.userId = null;
		this.firstName = null;
		this.lastName = null;
		this.email = null;
		this.gender = null;
		this.status = null;
	}
	
	public Map<String,Object> getUserSearchCriteriaMap(){
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("userId", "".equals(this.userId)?null:this.userId);
		map.put("lastName","".equals(this.lastName)?null:this.lastName);
		map.put("firstName","".equals(this.firstName)?null:this.firstName);
		map.put("age", "".equals(this.age)?null:this.age);
		map.put("email","".equals(this.email)?null:this.email);
		map.put("gender","".equals(this.gender)?null:this.gender);
		map.put("status","".equals(this.status)?null:this.status);
		return map;
	}
}

 

 

在service中,拿到bean中绑定好的参数名和值得map集合传入service中,并且调用DAO中的方法;

public List<User> getUserListPageByCriteria(UserSearchCriteria criteria,
			PageAttribute pga,Set<User> memberExistsUser)
			throws UserServiceException {
		
		// TODO Auto-generated method stub
		logger.info("Start getUserListPageByCriteria");
		final String endingMsg = "End getUserListPageByCriteria";
		logger.info("query record from "+pga.getStartIndex()+" to "+(pga.getStartIndex()+pga.getPageSize()));
		
		String hql = null;
		StringBuffer sb= new StringBuffer(" from User user where " +
				"(:firstName is null or user.firstName like concat(:firstName,'%') ) " +
				"and (:lastName is null or user.lastName like concat(:lastName,'%') ) " +
				"and (:age is null or user.age = :age) " +
				"and (:email is null or user.email = :email) " +
				"and (:gender is null or user.gender = :gender) " +
				"and (:status is null or user.status = :status) " +
				"and (:userId is null or user.userId = :userId) " );
			
		List<User> userList=null;
			try {
				if(memberExistsUser!=null && memberExistsUser.size()>0){
					sb.append("and ( user.userId not in ( ");
				
					for(User user:memberExistsUser){
						sb.append("'").append(user.getUserId()).append("'").append(",");
					}
					
					String resultStr= StringUtils.removeEnd(sb.toString(), ",")+"))";
					hql = resultStr;
				}else{
					hql = sb.toString();
				}
				
				Map<String,Object> paramMap = criteria.getUserSearchCriteriaMap();
				userList = userDao.getUserByQuery(paramMap, hql);
			} catch (DatabaseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("GetUserListPageByCriteria exception",e);
				throw new UserServiceException("GetUserListPageByCriteria exception",e);
			}
			logger.info(endingMsg);
			return userList;
	}

 

 

   DAO封装好的方法如下:

/**
	 * Query records by query
	 * 
	 * @param map
	 * @param queryString
	 * @return
	 * @throws DatabaseException
	 */
	@SuppressWarnings("unchecked")
	public <T> List<T> getObjectsByQuery(final Map<String, Object> map,
			final String queryString) throws DatabaseException {
		log.info("Start Get objects by HQL query [" + queryString + "]");
		final String endingMsg = "End getObjectsByQuery";
		if (map == null)
			throw new IllegalArgumentException("Mapping is null");
		if (queryString == null)
			throw new IllegalArgumentException("Query String is null");
		List<T> list = null;

		try {
			String[] params = map.keySet().toArray(new String[map.size()]);
			Object[] values = map.values().toArray(new Object[map.size()]);
			list = this.getHibernateTemplate().findByNamedParam(queryString,
					params, values);
		} catch (HibernateException e) {
			log.logExceptionCaught(e);
			throw new DatabaseException(e);
		} finally {
			log.info(endingMsg);
		}
		return list;
	}

 

 

 

调用Hibernate中的底层方法;

 

public List findByNamedParam(final String queryString, final String[] paramNames, final Object[] values)
			throws DataAccessException {

		if (paramNames.length != values.length) {
			throw new IllegalArgumentException("Length of paramNames array must match length of values array");
		}
		return (List) executeWithNativeSession(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = session.createQuery(queryString);
				prepareQuery(queryObject);
				if (values != null) {
					for (int i = 0; i < values.length; i++) {
						applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
					}
				}
				return queryObject.list();
			}
		});
	}