hibernatetemplate.java

来自「一个关于Spring框架的示例应用程序,简单使用,可以参考.」· Java 代码 · 共 1,216 行 · 第 1/3 页

JAVA
1,216
字号
	    throws DataAccessException {
		return findByNamedQueryAndNamedParam(queryName, paramNames, values);
	}

	/**
	 * @deprecated in favor of findByNamedQueryAndNamedParam,
	 * to avoid parameter overloading ambiguities
	 * @see #findByNamedQueryAndNamedParam
	 */
	public List findByNamedQuery(String queryName, String[] paramNames, Object[] values, Type[] types)
	    throws DataAccessException {
		return findByNamedQueryAndNamedParam(queryName, paramNames, values, types);
	}

	public List findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)
			throws DataAccessException {
		return findByNamedQueryAndNamedParam(queryName, paramName, value, null);
	}

	public List findByNamedQueryAndNamedParam(
	    final String queryName, final String paramName, final Object value, final Type type)
			throws DataAccessException {
		return (List) execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = getNamedQuery(session, queryName);
				applyNamedParameterToQuery(queryObject, paramName, value, type);
				return queryObject.list();
			}
		}, true);
	}

	public List findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values)
			throws DataAccessException {
		return findByNamedQueryAndNamedParam(queryName, paramNames, values, null);
	}

	public List findByNamedQueryAndNamedParam(
	    final String queryName, final String[] paramNames, final Object[] values, final Type[] types)
	    throws DataAccessException {
		if (paramNames.length != values.length) {
			throw new IllegalArgumentException("Length of paramNames array must match length of values array");
		}
		if (types != null && paramNames.length != types.length) {
			throw new IllegalArgumentException("Length of paramNames array must match length of types array");
		}
		return (List) execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = getNamedQuery(session, queryName);
				for (int i = 0; i < values.length; i++) {
					applyNamedParameterToQuery(queryObject, paramNames[i], values[i], (types != null ? types[i] : null));
				}
				return queryObject.list();
			}
		}, true);
	}

	public List findByNamedQueryAndValueBean(final String queryName, final Object valueBean)
			throws DataAccessException {
		return (List) execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = getNamedQuery(session, queryName);
				queryObject.setProperties(valueBean);
				return queryObject.list();
			}
		}, true);
	}


	//-------------------------------------------------------------------------
	// Convenience query methods for iterate and delete
	//-------------------------------------------------------------------------

	public Iterator iterate(final String queryString) throws DataAccessException {
		return (Iterator) execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = session.createQuery(queryString);
				prepareQuery(queryObject);
				return queryObject.iterate();
			}
		}, true);
	}

	public Iterator iterate(String queryString, Object value) throws DataAccessException {
		return iterate(queryString, value, null);
	}

	public Iterator iterate(final String queryString, final Object value, final Type type)
			throws DataAccessException {
		return (Iterator) execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = session.createQuery(queryString);
				prepareQuery(queryObject);
				if (type != null) {
					queryObject.setParameter(0, value, type);
				}
				else {
					queryObject.setParameter(0, value);
				}
				return queryObject.iterate();
			}
		}, true);
	}

	public Iterator iterate(String queryString, Object[] values) throws DataAccessException {
		return iterate(queryString, values, (Type[]) null);
	}

	public Iterator iterate(final String queryString, final Object[] values, final Type[] types)
			throws DataAccessException {
		if (types != null && values.length != types.length) {
			throw new IllegalArgumentException("Length of values array must match length of types array");
		}
		return (Iterator) execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query queryObject = session.createQuery(queryString);
				prepareQuery(queryObject);
				for (int i = 0; i < values.length; i++) {
					if (types != null) {
						queryObject.setParameter(i, values[i], types[i]);
					}
					else {
						queryObject.setParameter(i, values[i]);
					}
				}
				return queryObject.iterate();
			}
		}, true);
	}

	public void closeIterator(Iterator it) throws DataAccessException {
		try {
			Hibernate.close(it);
		}
		catch (HibernateException ex) {
			throw SessionFactoryUtils.convertHibernateAccessException(ex);
		}
	}

	public int delete(final String queryString) throws DataAccessException {
		Integer deleteCount = (Integer) execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				checkWriteOperationAllowed(session);
				return new Integer(session.delete(queryString));
			}
		}, true);
		return deleteCount.intValue();
	}

	public int delete(final String queryString, final Object value, final Type type)
			throws DataAccessException {
		Integer deleteCount = (Integer) execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				checkWriteOperationAllowed(session);
				return new Integer(session.delete(queryString, value, type));
			}
		}, true);
		return deleteCount.intValue();
	}

	public int delete(final String queryString, final Object[] values, final Type[] types)
			throws DataAccessException {
		Integer deleteCount = (Integer) execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				checkWriteOperationAllowed(session);
				return new Integer(session.delete(queryString, values, types));
			}
		}, true);
		return deleteCount.intValue();
	}


	/**
	 * Check whether write operations are allowed on the given Session.
	 * <p>Default implementation throws an InvalidDataAccessApiUsageException
	 * in case of FlushMode.NEVER. Can be overridden in subclasses.
	 * @param session current Hibernate Session
	 * @throws InvalidDataAccessApiUsageException if write operations are not allowed
	 * @see #setCheckWriteOperations
	 * @see #getFlushMode
	 * @see #FLUSH_EAGER
	 * @see net.sf.hibernate.Session#getFlushMode
	 * @see net.sf.hibernate.FlushMode#NEVER
	 */
	protected void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException {
		if (isCheckWriteOperations() && getFlushMode() != FLUSH_EAGER &&
				FlushMode.NEVER.equals(session.getFlushMode())) {
			throw new InvalidDataAccessApiUsageException(
					"Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session " +
					"into FlushMode.AUTO or remove 'readOnly' marker from transaction definition");
		}
	}

	/**
	 * Prepare the given Query object, applying cache settings and/or
	 * a transaction timeout.
	 * @param queryObject the Query object to prepare
	 * @see #setCacheQueries
	 * @see #setQueryCacheRegion
	 * @see SessionFactoryUtils#applyTransactionTimeout
	 */
	protected void prepareQuery(Query queryObject) {
		if (isCacheQueries()) {
			queryObject.setCacheable(true);
			if (getQueryCacheRegion() != null) {
				queryObject.setCacheRegion(getQueryCacheRegion());
			}
		}
		SessionFactoryUtils.applyTransactionTimeout(queryObject, getSessionFactory());
	}

	/**
	 * Prepare the given Criteria object, applying cache settings and/or
	 * a transaction timeout.
	 * @param criteria the Criteria object to prepare
	 * @see #setCacheQueries
	 * @see #setQueryCacheRegion
	 * @see SessionFactoryUtils#applyTransactionTimeout
	 */
	protected void prepareCriteria(Criteria criteria) {
		if (isCacheQueries()) {
			criteria.setCacheable(true);
			if (getQueryCacheRegion() != null) {
				criteria.setCacheRegion(getQueryCacheRegion());
			}
		}
		SessionFactoryUtils.applyTransactionTimeout(criteria, getSessionFactory());
	}

	/**
	 * Apply the given name parameter to the given Query object.
	 * @param queryObject the Query object
	 * @param paramName the name of the parameter
	 * @param value the value of the parameter
	 * @param type Hibernate type of the parameter (or null if none specified)
	 * @throws HibernateException if thrown by the Query object
	 */
	protected void applyNamedParameterToQuery(Query queryObject, String paramName, Object value, Type type)
			throws HibernateException {
		if (value instanceof Collection) {
			if (type != null) {
				queryObject.setParameterList(paramName, (Collection) value, type);
			}
			else {
				queryObject.setParameterList(paramName, (Collection) value);
			}
		}
		else if (value instanceof Object[]) {
			if (type != null) {
				queryObject.setParameterList(paramName, (Object[]) value, type);
			}
			else {
				queryObject.setParameterList(paramName, (Object[]) value);
			}
		}
		else {
			if (type != null) {
				queryObject.setParameter(paramName, value, type);
			}
			else {
				queryObject.setParameter(paramName, value);
			}
		}
	}


	/**
	 * Create a Query object for the given Session and the given query string.
	 * <b>To be used within a HibernateCallback</b>:
	 * <pre>
	 * List result = hibernateTemplate.executeFind(new HibernateCallback() {
	 *   public Object doInHibernate(Session session) throws HibernateException {
	 *     Query query = hibernateTemplate.createQuery(session, "...");
	 *     ...
	 *     return query.list();
	 *   }
	 * });</pre>
	 * Applies query cache settings and a transaction timeout, if any. If you don't
	 * use either of those, the call is equivalent to <code>Session.createQuery</code>.
	 * @param session current Hibernate Session
	 * @param queryString the HQL query string
	 * @return the Query object
	 * @throws HibernateException if the Query could not be created
	 * @deprecated Use <code>session.createQuery</code> instead, which will now
	 * automatically apply the template's query cache settings and the transaction
	 * timeout (through the use of a special Session proxy).
	 * @see HibernateCallback#doInHibernate
	 * @see #setCacheQueries
	 * @see SessionFactoryUtils#applyTransactionTimeout
	 * @see net.sf.hibernate.Session#createQuery
	 */
	public Query createQuery(Session session, String queryString) throws HibernateException {
		Query queryObject = session.createQuery(queryString);
		prepareQuery(queryObject);
		return queryObject;
	}

	/**
	 * Create a named Query object for the given Session and the given query name.
	 * <b>To be used within a HibernateCallback</b>:
	 * <pre>
	 * List result = hibernateTemplate.executeFind(new HibernateCallback() {
	 *   public Object doInHibernate(Session session) throws HibernateException {
	 *     Query query = hibernateTemplate.getNamedQuery(session, "...");
	 *     ...
	 *     return query.list();
	 *   }
	 * });</pre>
	 * Applies query cache settings and a transaction timeout, if any. If you don't
	 * use either of those, the call is equivalent to <code>Session.getNamedQuery</code>.
	 * @param session current Hibernate Session
	 * @param queryName the name of the query in the Hibernate mapping file
	 * @return the Query object
	 * @throws HibernateException if the Query could not be created
	 * @deprecated Use <code>session.getNamedQuery</code> instead, which will now
	 * automatically apply the template's query cache settings and the transaction
	 * timeout (through the use of a special Session proxy).
	 * @see HibernateCallback#doInHibernate
	 * @see #setCacheQueries
	 * @see SessionFactoryUtils#applyTransactionTimeout
	 * @see net.sf.hibernate.Session#getNamedQuery
	 */
	public Query getNamedQuery(Session session, String queryName) throws HibernateException {
		Query queryObject = session.getNamedQuery(queryName);
		prepareQuery(queryObject);
		return queryObject;
	}

	/**
	 * Create a Criteria object for the given Session and the given entity class.
	 * <b>To be used within a HibernateCallback</b>:
	 * <pre>
	 * List result = hibernateTemplate.executeFind(new HibernateCallback() {
	 *   public Object doInHibernate(Session session) throws HibernateException {
	 *     Criteria criteria = hibernateTemplate.createCriteria(session, MyClass.class);
	 *     ...
	 *     return query.list();
	 *   }
	 * });</pre>
	 * Applies query cache settings and a transaction timeout, if any. If you don't
	 * use either of those, the call is equivalent to <code>Session.createCriteria</code>.
	 * @param session current Hibernate Session
	 * @param entityClass the entity class to create the Criteria for
	 * @return the Query object
	 * @throws HibernateException if the Criteria could not be created
	 * @deprecated Use <code>session.createCriteria</code> instead, which will now
	 * automatically apply the template's query cache settings and the transaction
	 * timeout (through the use of a special Session proxy).
	 * @see HibernateCallback#doInHibernate
	 * @see #setCacheQueries
	 * @see #setQueryCacheRegion
	 * @see SessionFactoryUtils#applyTransactionTimeout
	 * @see net.sf.hibernate.Session#createCriteria
	 */
	public Criteria createCriteria(Session session, Class entityClass) throws HibernateException {
		Criteria criteria = session.createCriteria(entityClass);
		prepareCriteria(criteria);
		return criteria;
	}


	/**
	 * Invocation handler that suppresses close calls on Hibernate Sessions.
	 * Also prepares returned Query and Criteria objects.
	 * @see net.sf.hibernate.Session#close
	 */
	private class CloseSuppressingInvocationHandler implements InvocationHandler {

		private static final String SESSION_CLOSE_METHOD_NAME = "close";

		private final Session target;

		public CloseSuppressingInvocationHandler(Session target) {
			this.target = target;
		}

		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			// Handle close method: suppress, not valid.
			if (method.getName().equals(SESSION_CLOSE_METHOD_NAME)) {
				return null;
			}

			// Invoke method on target Session.
			try {
				Object retVal = method.invoke(this.target, args);

				// If return value is a Query or Criteria, apply transaction timeout.
				// Applies to createQuery, getNamedQuery, createCriteria.
				if (retVal instanceof Query) {
					prepareQuery(((Query) retVal));
				}
				if (retVal instanceof Criteria) {
					prepareCriteria(((Criteria) retVal));
				}

				return retVal;
			}
			catch (InvocationTargetException ex) {
				throw ex.getTargetException();
			}
		}
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?