📄 hibernatetemplate.java
字号:
}
public void clear() throws DataAccessException {
execute(new HibernateCallback() {
public Object doInHibernate(Session session) {
session.clear();
return null;
}
}, true);
}
//-------------------------------------------------------------------------
// Convenience finder methods for HQL strings
//-------------------------------------------------------------------------
public List find(String queryString) throws DataAccessException {
return find(queryString, (Object[]) null);
}
public List find(String queryString, Object value) throws DataAccessException {
return find(queryString, new Object[] {value});
}
public List find(final String queryString, final Object[] values) throws DataAccessException {
return (List) execute(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++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject.list();
}
}, true);
}
public List findByNamedParam(String queryString, String paramName, Object value)
throws DataAccessException {
return findByNamedParam(queryString, new String[] {paramName}, new Object[] {value});
}
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) execute(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();
}
}, true);
}
public List findByValueBean(final String queryString, final Object valueBean)
throws DataAccessException {
return (List) execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.createQuery(queryString);
prepareQuery(queryObject);
queryObject.setProperties(valueBean);
return queryObject.list();
}
}, true);
}
//-------------------------------------------------------------------------
// Convenience finder methods for named queries
//-------------------------------------------------------------------------
public List findByNamedQuery(String queryName) throws DataAccessException {
return findByNamedQuery(queryName, (Object[]) null);
}
public List findByNamedQuery(String queryName, Object value) throws DataAccessException {
return findByNamedQuery(queryName, new Object[] {value});
}
public List findByNamedQuery(final String queryName, final Object[] values) throws DataAccessException {
return (List) execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.getNamedQuery(queryName);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject.list();
}
}, true);
}
public List findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)
throws DataAccessException {
return findByNamedQueryAndNamedParam(queryName, new String[] {paramName}, new Object[] {value});
}
public List findByNamedQueryAndNamedParam(
final String queryName, final String[] paramNames, final Object[] values)
throws DataAccessException {
if (paramNames != null && values != null && paramNames.length != values.length) {
throw new IllegalArgumentException("Length of paramNames array must match length of values array");
}
return (List) execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query queryObject = session.getNamedQuery(queryName);
prepareQuery(queryObject);
if (values != null) {
for (int i = 0; i < values.length; i++) {
applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
}
}
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 = session.getNamedQuery(queryName);
prepareQuery(queryObject);
queryObject.setProperties(valueBean);
return queryObject.list();
}
}, true);
}
//-------------------------------------------------------------------------
// Convenience finder methods for detached criteria
//-------------------------------------------------------------------------
public List findByCriteria(DetachedCriteria criteria) throws DataAccessException {
return findByCriteria(criteria, -1, -1);
}
public List findByCriteria(final DetachedCriteria criteria, final int firstResult, final int maxResults)
throws DataAccessException {
Assert.notNull(criteria, "DetachedCriteria must not be null");
return (List) execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria executableCriteria = criteria.getExecutableCriteria(session);
prepareCriteria(executableCriteria);
if (firstResult >= 0) {
executableCriteria.setFirstResult(firstResult);
}
if (maxResults > 0) {
executableCriteria.setMaxResults(maxResults);
}
return executableCriteria.list();
}
}, true);
}
public List findByExample(Object exampleEntity) throws DataAccessException {
return findByExample(exampleEntity, -1, -1);
}
public List findByExample(final Object exampleEntity, final int firstResult, final int maxResults)
throws DataAccessException {
Assert.notNull(exampleEntity, "Example entity must not be null");
return (List) execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria executableCriteria = session.createCriteria(exampleEntity.getClass());
executableCriteria.add(Example.create(exampleEntity));
prepareCriteria(executableCriteria);
if (firstResult >= 0) {
executableCriteria.setFirstResult(firstResult);
}
if (maxResults > 0) {
executableCriteria.setMaxResults(maxResults);
}
return executableCriteria.list();
}
}, true);
}
//-------------------------------------------------------------------------
// Convenience query methods for iteration and bulk updates/deletes
//-------------------------------------------------------------------------
public Iterator iterate(String queryString) throws DataAccessException {
return iterate(queryString, (Object[]) null);
}
public Iterator iterate(String queryString, Object value) throws DataAccessException {
return iterate(queryString, new Object[] {value});
}
public Iterator iterate(final String queryString, final Object[] values) throws DataAccessException {
return (Iterator) execute(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++) {
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 bulkUpdate(String queryString) throws DataAccessException {
return bulkUpdate(queryString, (Object[]) null);
}
public int bulkUpdate(String queryString, Object value) throws DataAccessException {
return bulkUpdate(queryString, new Object[] {value});
}
public int bulkUpdate(final String queryString, final Object[] values) throws DataAccessException {
Integer updateCount = (Integer) execute(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++) {
queryObject.setParameter(i, values[i]);
}
}
return new Integer(queryObject.executeUpdate());
}
}, true);
return updateCount.intValue();
}
//-------------------------------------------------------------------------
// Helper methods used by the operations above
//-------------------------------------------------------------------------
/**
* 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 org.hibernate.Session#getFlushMode
* @see org.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());
}
}
if (getFetchSize() > 0) {
queryObject.setFetchSize(getFetchSize());
}
if (getMaxResults() > 0) {
queryObject.setMaxResults(getMaxResults());
}
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());
}
}
if (getFetchSize() > 0) {
criteria.setFetchSize(getFetchSize());
}
if (getMaxResults() > 0) {
criteria.setMaxResults(getMaxResults());
}
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
* @throws HibernateException if thrown by the Query object
*/
protected void applyNamedParameterToQuery(Query queryObject, String paramName, Object value)
throws HibernateException {
if (value instanceof Collection) {
queryObject.setParameterList(paramName, (Collection) value);
}
else if (value instanceof Object[]) {
queryObject.setParameterList(paramName, (Object[]) value);
}
else {
queryObject.setParameter(paramName, value);
}
}
/**
* Invocation handler that suppresses close calls on Hibernate Sessions.
* Also prepares returned Query and Criteria objects.
* @see org.hibernate.Session#close
*/
private class CloseSuppressingInvocationHandler implements InvocationHandler {
private final Session target;
public CloseSuppressingInvocationHandler(Session target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Invocation on Session interface coming in...
if (method.getName().equals("equals")) {
// Only consider equal when proxies are identical.
return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);
}
else if (method.getName().equals("hashCode")) {
// Use hashCode of Session proxy.
return new Integer(hashCode());
}
else if (method.getName().equals("close")) {
// Handle close method: suppress, not valid.
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -