`

HibernateTemplate

 
阅读更多

HibernateTemplate源码


  1.   
  2.   
  3. package org.springframework.orm.hibernate3;  
  4.   
  5. import java.io.Serializable;  
  6. import java.lang.reflect.InvocationHandler;  
  7. import java.lang.reflect.InvocationTargetException;  
  8. import java.lang.reflect.Method;  
  9. import java.lang.reflect.Proxy;  
  10. import java.sql.SQLException;  
  11. import java.util.Collection;  
  12. import java.util.Iterator;  
  13. import java.util.List;  
  14.   
  15. import org.hibernate.Criteria;  
  16. import org.hibernate.Filter;  
  17. import org.hibernate.FlushMode;  
  18. import org.hibernate.Hibernate;  
  19. import org.hibernate.HibernateException;  
  20. import org.hibernate.LockMode;  
  21. import org.hibernate.Query;  
  22. import org.hibernate.ReplicationMode;  
  23. import org.hibernate.Session;  
  24. import org.hibernate.SessionFactory;  
  25. import org.hibernate.criterion.DetachedCriteria;  
  26. import org.hibernate.criterion.Example;  
  27. import org.hibernate.engine.SessionImplementor;  
  28. import org.hibernate.event.EventSource;  
  29.   
  30. import org.springframework.dao.DataAccessException;  
  31. import org.springframework.dao.DataAccessResourceFailureException;  
  32. import org.springframework.dao.InvalidDataAccessApiUsageException;  
  33. import org.springframework.util.Assert;  
  34.   
  35.   
  36. public class HibernateTemplate extends HibernateAccessor implements HibernateOperations {  
  37.   
  38.     private boolean allowCreate = true;  
  39.   
  40.     private boolean alwaysUseNewSession = false;  
  41.   
  42.     private boolean exposeNativeSession = false;  
  43.   
  44.     private boolean checkWriteOperations = true;  
  45.   
  46.     private boolean cacheQueries = false;  
  47.   
  48.     private String queryCacheRegion;  
  49.   
  50.     private int fetchSize = 0;  
  51.   
  52.     private int maxResults = 0;  
  53.   
  54.   
  55.       
  56.     public HibernateTemplate() {  
  57.     }  
  58.   
  59.       
  60.     public HibernateTemplate(SessionFactory sessionFactory) {  
  61.         setSessionFactory(sessionFactory);  
  62.         afterPropertiesSet();  
  63.     }  
  64.   
  65.       
  66.     public HibernateTemplate(SessionFactory sessionFactory, boolean allowCreate) {  
  67.         setSessionFactory(sessionFactory);  
  68.         setAllowCreate(allowCreate);  
  69.         afterPropertiesSet();  
  70.     }  
  71.   
  72.   
  73.       
  74.     public void setAllowCreate(boolean allowCreate) {  
  75.         this.allowCreate = allowCreate;  
  76.     }  
  77.   
  78.       
  79.     public boolean isAllowCreate() {  
  80.         return this.allowCreate;  
  81.     }  
  82.   
  83.       
  84.     public void setAlwaysUseNewSession(boolean alwaysUseNewSession) {  
  85.         this.alwaysUseNewSession = alwaysUseNewSession;  
  86.     }  
  87.   
  88.       
  89.     public boolean isAlwaysUseNewSession() {  
  90.         return this.alwaysUseNewSession;  
  91.     }  
  92.   
  93.       
  94.     public void setExposeNativeSession(boolean exposeNativeSession) {  
  95.         this.exposeNativeSession = exposeNativeSession;  
  96.     }  
  97.   
  98.       
  99.     public boolean isExposeNativeSession() {  
  100.         return this.exposeNativeSession;  
  101.     }  
  102.   
  103.       
  104.     public void setCheckWriteOperations(boolean checkWriteOperations) {  
  105.         this.checkWriteOperations = checkWriteOperations;  
  106.     }  
  107.   
  108.       
  109.     public boolean isCheckWriteOperations() {  
  110.         return this.checkWriteOperations;  
  111.     }  
  112.   
  113.       
  114.     public void setCacheQueries(boolean cacheQueries) {  
  115.         this.cacheQueries = cacheQueries;  
  116.     }  
  117.   
  118.       
  119.     public boolean isCacheQueries() {  
  120.         return this.cacheQueries;  
  121.     }  
  122.   
  123.       
  124.     public void setQueryCacheRegion(String queryCacheRegion) {  
  125.         this.queryCacheRegion = queryCacheRegion;  
  126.     }  
  127.   
  128.       
  129.     public String getQueryCacheRegion() {  
  130.         return this.queryCacheRegion;  
  131.     }  
  132.   
  133.       
  134.     public void setFetchSize(int fetchSize) {  
  135.         this.fetchSize = fetchSize;  
  136.     }  
  137.   
  138.       
  139.     public int getFetchSize() {  
  140.         return this.fetchSize;  
  141.     }  
  142.   
  143.       
  144.     public void setMaxResults(int maxResults) {  
  145.         this.maxResults = maxResults;  
  146.     }  
  147.   
  148.       
  149.     public int getMaxResults() {  
  150.         return this.maxResults;  
  151.     }  
  152.   
  153.   
  154.     public Object execute(HibernateCallback action) throws DataAccessException {  
  155.         return doExecute(action, false, false);  
  156.     }  
  157.   
  158.     public List executeFind(HibernateCallback action) throws DataAccessException {  
  159.         Object result = doExecute(action, false, false);  
  160.         if (result != null && !(result instanceof List)) {  
  161.             throw new InvalidDataAccessApiUsageException(  
  162.                     "Result object returned from HibernateCallback isn't a List: [" + result + "]");  
  163.         }  
  164.         return (List) result;  
  165.     }  
  166.   
  167.       
  168.     public Object executeWithNewSession(HibernateCallback action) {  
  169.         return doExecute(action, true, false);  
  170.     }  
  171.   
  172.       
  173.     public Object executeWithNativeSession(HibernateCallback action) {  
  174.         return doExecute(action, false, true);  
  175.     }  
  176.   
  177.       
  178.     public Object execute(HibernateCallback action, boolean enforceNativeSession) throws DataAccessException {  
  179.         return doExecute(action, false, enforceNativeSession);  
  180.     }  
  181.   
  182.       
  183.     protected Object doExecute(HibernateCallback action, boolean enforceNewSession, boolean enforceNativeSession)  
  184.             throws DataAccessException {  
  185.   
  186.         Assert.notNull(action, "Callback object must not be null");  
  187.   
  188.         Session session = (enforceNewSession ?  
  189.                 SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor()) : getSession());  
  190.         boolean existingTransaction = (!enforceNewSession &&  
  191.                 (!isAllowCreate() || SessionFactoryUtils.isSessionTransactional(session, getSessionFactory())));  
  192.         if (existingTransaction) {  
  193.             logger.debug("Found thread-bound Session for HibernateTemplate");  
  194.         }  
  195.   
  196.         FlushMode previousFlushMode = null;  
  197.         try {  
  198.             previousFlushMode = applyFlushMode(session, existingTransaction);  
  199.             enableFilters(session);  
  200.             Session sessionToExpose =  
  201.                     (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));  
  202.             Object result = action.doInHibernate(sessionToExpose);  
  203.             flushIfNecessary(session, existingTransaction);  
  204.             return result;  
  205.         }  
  206.         catch (HibernateException ex) {  
  207.             throw convertHibernateAccessException(ex);  
  208.         }  
  209.         catch (SQLException ex) {  
  210.             throw convertJdbcAccessException(ex);  
  211.         }  
  212.         catch (RuntimeException ex) {  
  213.             // Callback code threw application exception...  
  214.             throw ex;  
  215.         }  
  216.         finally {  
  217.             if (existingTransaction) {  
  218.                 logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");  
  219.                 disableFilters(session);  
  220.                 if (previousFlushMode != null) {  
  221.                     session.setFlushMode(previousFlushMode);  
  222.                 }  
  223.             }  
  224.             else {  
  225.                 // Never use deferred close for an explicitly new Session.  
  226.                 if (isAlwaysUseNewSession()) {  
  227.                     SessionFactoryUtils.closeSession(session);  
  228.                 }  
  229.                 else {  
  230.                     SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());  
  231.                 }  
  232.             }  
  233.         }  
  234.     }  
  235.   
  236.       
  237.     protected Session getSession() {  
  238.         if (isAlwaysUseNewSession()) {  
  239.             return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());  
  240.         }  
  241.         else if (isAllowCreate()) {  
  242.             return SessionFactoryUtils.getSession(  
  243.                     getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());  
  244.         }  
  245.         else {  
  246.             try {  
  247.                 return getSessionFactory().getCurrentSession();  
  248.             }  
  249.             catch (HibernateException ex) {  
  250.                 throw new DataAccessResourceFailureException("Could not obtain current Hibernate Session", ex);  
  251.             }  
  252.         }  
  253.     }  
  254.   
  255.       
  256.     protected Session createSessionProxy(Session session) {  
  257.         Class[] sessionIfcs = null;  
  258.         Class mainIfc = (session instanceof org.hibernate.classic.Session ?  
  259.                 org.hibernate.classic.Session.class : Session.class);  
  260.         if (session instanceof EventSource) {  
  261.             sessionIfcs = new Class[] {mainIfc, EventSource.class};  
  262.         }  
  263.         else if (session instanceof SessionImplementor) {  
  264.             sessionIfcs = new Class[] {mainIfc, SessionImplementor.class};  
  265.         }  
  266.         else {  
  267.             sessionIfcs = new Class[] {mainIfc};  
  268.         }  
  269.         return (Session) Proxy.newProxyInstance(  
  270.                 getClass().getClassLoader(), sessionIfcs,  
  271.                 new CloseSuppressingInvocationHandler(session));  
  272.     }  
  273.   
  274.   
  275.     //-------------------------------------------------------------------------  
  276.     // Convenience methods for loading individual objects  
  277.     //-------------------------------------------------------------------------  
  278.   
  279.     public Object get(Class entityClass, Serializable id) throws DataAccessException {  
  280.         return get(entityClass, id, null);  
  281.     }  
  282.   
  283.     public Object get(final Class entityClass, final Serializable id, final LockMode lockMode)  
  284.             throws DataAccessException {  
  285.   
  286.         return executeWithNativeSession(new HibernateCallback() {  
  287.             public Object doInHibernate(Session session) throws HibernateException {  
  288.                 if (lockMode != null) {  
  289.                     return session.get(entityClass, id, lockMode);  
  290.                 }  
  291.                 else {  
  292.                     return session.get(entityClass, id);  
  293.                 }  
  294.             }  
  295.         });  
  296.     }  
  297.   
  298.     public Object get(String entityName, Serializable id) throws DataAccessException {  
  299.         return get(entityName, id, null);  
  300.     }  
  301.   
  302.     public Object get(final String entityName, final Serializable id, final LockMode lockMode)  
  303.             throws DataAccessException {  
  304.   
  305.         return executeWithNativeSession(new HibernateCallback() {  
  306.             public Object doInHibernate(Session session) throws HibernateException {  
  307.                 if (lockMode != null) {  
  308.                     return session.get(entityName, id, lockMode);  
  309.                 }  
  310.                 else {  
  311.                     return session.get(entityName, id);  
  312.                 }  
  313.             }  
  314.         });  
  315.     }  
  316.   
  317.     public Object load(Class entityClass, Serializable id) throws DataAccessException {  
  318.         return load(entityClass, id, null);  
  319.     }  
  320.   
  321.     public Object load(final Class entityClass, final Serializable id, final LockMode lockMode)  
  322.             throws DataAccessException {  
  323.   
  324.         return executeWithNativeSession(new HibernateCallback() {  
  325.             public Object doInHibernate(Session session) throws HibernateException {  
  326.                 if (lockMode != null) {  
  327.                     return session.load(entityClass, id, lockMode);  
  328.                 }  
  329.                 else {  
  330.                     return session.load(entityClass, id);  
  331.                 }  
  332.             }  
  333.         });  
  334.     }  
  335.   
  336.     public Object load(String entityName, Serializable id) throws DataAccessException {  
  337.         return load(entityName, id, null);  
  338.     }  
  339.   
  340.     public Object load(final String entityName, final Serializable id, final LockMode lockMode)  
  341.             throws DataAccessException {  
  342.   
  343.         return executeWithNativeSession(new HibernateCallback() {  
  344.             public Object doInHibernate(Session session) throws HibernateException {  
  345.                 if (lockMode != null) {  
  346.                     return session.load(entityName, id, lockMode);  
  347.                 }  
  348.                 else {  
  349.                     return session.load(entityName, id);  
  350.                 }  
  351.             }  
  352.         });  
  353.     }  
  354.   
  355.     public List loadAll(final Class entityClass) throws DataAccessException {  
  356.         return (List) executeWithNativeSession(new HibernateCallback() {  
  357.             public Object doInHibernate(Session session) throws HibernateException {  
  358.                 Criteria criteria = session.createCriteria(entityClass);  
  359.                 prepareCriteria(criteria);  
  360.                 return criteria.list();  
  361.             }  
  362.         });  
  363.     }  
  364.   
  365.     public void load(final Object entity, final Serializable id) throws DataAccessException {  
  366.         executeWithNativeSession(new HibernateCallback() {  
  367.             public Object doInHibernate(Session session) throws HibernateException {  
  368.                 session.load(entity, id);  
  369.                 return null;  
  370.             }  
  371.         });  
  372.     }  
  373.   
  374.     public void refresh(final Object entity) throws DataAccessException {  
  375.         refresh(entity, null);  
  376.     }  
  377.   
  378.     public void refresh(final Object entity, final LockMode lockMode) throws DataAccessException {  
  379.         executeWithNativeSession(new HibernateCallback() {  
  380.             public Object doInHibernate(Session session) throws HibernateException {  
  381.                 if (lockMode != null) {  
  382.                     session.refresh(entity, lockMode);  
  383.                 }  
  384.                 else {  
  385.                     session.refresh(entity);  
  386.                 }  
  387.                 return null;  
  388.             }  
  389.         });  
  390.     }  
  391.   
  392.     public boolean contains(final Object entity) throws DataAccessException {  
  393.         Boolean result = (Boolean) executeWithNativeSession(new HibernateCallback() {  
  394.             public Object doInHibernate(Session session) {  
  395.                 return (session.contains(entity) ? Boolean.TRUE : Boolean.FALSE);  
  396.             }  
  397.         });  
  398.         return result.booleanValue();  
  399.     }  
  400.   
  401.     public void evict(final Object entity) throws DataAccessException {  
  402.         executeWithNativeSession(new HibernateCallback() {  
  403.             public Object doInHibernate(Session session) throws HibernateException {  
  404.                 session.evict(entity);  
  405.                 return null;  
  406.             }  
  407.         });  
  408.     }  
  409.   
  410.     public void initialize(Object proxy) throws DataAccessException {  
  411.         try {  
  412.             Hibernate.initialize(proxy);  
  413.         }  
  414.         catch (HibernateException ex) {  
  415.             throw SessionFactoryUtils.convertHibernateAccessException(ex);  
  416.         }  
  417.     }  
  418.   
  419.     public Filter enableFilter(String filterName) throws IllegalStateException {  
  420.         Session session = SessionFactoryUtils.getSession(getSessionFactory(), false);  
  421.         Filter filter = session.getEnabledFilter(filterName);  
  422.         if (filter == null) {  
  423.             filter = session.enableFilter(filterName);  
  424.         }  
  425.         return filter;  
  426.     }  
  427.   
  428.   
  429.     //-------------------------------------------------------------------------  
  430.     // Convenience methods for storing individual objects  
  431.     //-------------------------------------------------------------------------  
  432.   
  433.     public void lock(final Object entity, final LockMode lockMode) throws DataAccessException {  
  434.         executeWithNativeSession(new HibernateCallback() {  
  435.             public Object doInHibernate(Session session) throws HibernateException {  
  436.                 session.lock(entity, lockMode);  
  437.                 return null;  
  438.             }  
  439.         });  
  440.     }  
  441.   
  442.     public void lock(final String entityName, final Object entity, final LockMode lockMode)  
  443.             throws DataAccessException {  
  444.   
  445.         executeWithNativeSession(new HibernateCallback() {  
  446.             public Object doInHibernate(Session session) throws HibernateException {  
  447.                 session.lock(entityName, entity, lockMode);  
  448.                 return null;  
  449.             }  
  450.         });  
  451.     }  
  452.   
  453.     public Serializable save(final Object entity) throws DataAccessException {  
  454.         return (Serializable) executeWithNativeSession(new HibernateCallback() {  
  455.             public Object doInHibernate(Session session) throws HibernateException {  
  456.                 checkWriteOperationAllowed(session);  
  457.                 return session.save(entity);  
  458.             }  
  459.         });  
  460.     }  
  461.   
  462.     public Serializable save(final String entityName, final Object entity) throws DataAccessException {  
  463.         return (Serializable) executeWithNativeSession(new HibernateCallback() {  
  464.             public Object doInHibernate(Session session) throws HibernateException {  
  465.                 checkWriteOperationAllowed(session);  
  466.                 return session.save(entityName, entity);  
  467.             }  
  468.         });  
  469.     }  
  470.   
  471.     public void update(Object entity) throws DataAccessException {  
  472.         update(entity, null);  
  473.     }  
  474.   
  475.     public void update(final Object entity, final LockMode lockMode) throws DataAccessException {  
  476.         executeWithNativeSession(new HibernateCallback() {  
  477.             public Object doInHibernate(Session session) throws HibernateException {  
  478.                 checkWriteOperationAllowed(session);  
  479.                 session.update(entity);  
  480.                 if (lockMode != null) {  
  481.                     session.lock(entity, lockMode);  
  482.                 }  
  483.                 return null;  
  484.             }  
  485.         });  
  486.     }  
  487.   
  488.     public void update(String entityName, Object entity) throws DataAccessException {  
  489.         update(entityName, entity, null);  
  490.     }  
  491.   
  492.     public void update(final String entityName, final Object entity, final LockMode lockMode)  
  493.             throws DataAccessException {  
  494.   
  495.         executeWithNativeSession(new HibernateCallback() {  
  496.             public Object doInHibernate(Session session) throws HibernateException {  
  497.                 checkWriteOperationAllowed(session);  
  498.                 session.update(entityName, entity);  
  499.                 if (lockMode != null) {  
  500.                     session.lock(entity, lockMode);  
  501.                 }  
  502.                 return null;  
  503.             }  
  504.         });  
  505.     }  
  506.   
  507.     public void saveOrUpdate(final Object entity) throws DataAccessException {  
  508.         executeWithNativeSession(new HibernateCallback() {  
  509.             public Object doInHibernate(Session session) throws HibernateException {  
  510.                 checkWriteOperationAllowed(session);  
  511.                 session.saveOrUpdate(entity);  
  512.                 return null;  
  513.             }  
  514.         });  
  515.     }  
  516.   
  517.     public void saveOrUpdate(final String entityName, final Object entity) throws DataAccessException {  
  518.         executeWithNativeSession(new HibernateCallback() {  
  519.             public Object doInHibernate(Session session) throws HibernateException {  
  520.                 checkWriteOperationAllowed(session);  
  521.                 session.saveOrUpdate(entityName, entity);  
  522.                 return null;  
  523.             }  
  524.         });  
  525.     }  
  526.   
  527.     public void saveOrUpdateAll(final Collection entities) throws DataAccessException {  
  528.         executeWithNativeSession(new HibernateCallback() {  
  529.             public Object doInHibernate(Session session) throws HibernateException {  
  530.                 checkWriteOperationAllowed(session);  
  531.                 for (Iterator it = entities.iterator(); it.hasNext();) {  
  532.                     session.saveOrUpdate(it.next());  
  533.                 }  
  534.                 return null;  
  535.             }  
  536.         });  
  537.     }  
  538.   
  539.     public void replicate(final Object entity, final ReplicationMode replicationMode)  
  540.             throws DataAccessException {  
  541.   
  542.         executeWithNativeSession(new HibernateCallback() {  
  543.             public Object doInHibernate(Session session) throws HibernateException {  
  544.                 checkWriteOperationAllowed(session);  
  545.                 session.replicate(entity, replicationMode);  
  546.                 return null;  
  547.             }  
  548.         });  
  549.     }  
  550.   
  551.     public void replicate(final String entityName, final Object entity, final ReplicationMode replicationMode)  
  552.             throws DataAccessException {  
  553.   
  554.         executeWithNativeSession(new HibernateCallback() {  
  555.             public Object doInHibernate(Session session) throws HibernateException {  
  556.                 checkWriteOperationAllowed(session);  
  557.                 session.replicate(entityName, entity, replicationMode);  
  558.                 return null;  
  559.             }  
  560.         });  
  561.     }  
  562.   
  563.     public void persist(final Object entity) throws DataAccessException {  
  564.         executeWithNativeSession(new HibernateCallback() {  
  565.             public Object doInHibernate(Session session) throws HibernateException {  
  566.                 checkWriteOperationAllowed(session);  
  567.                 session.persist(entity);  
  568.                 return null;  
  569.             }  
  570.         });  
  571.     }  
  572.   
  573.     public void persist(final String entityName, final Object entity) throws DataAccessException {  
  574.         executeWithNativeSession(new HibernateCallback() {  
  575.             public Object doInHibernate(Session session) throws HibernateException {  
  576.                 checkWriteOperationAllowed(session);  
  577.                 session.persist(entityName, entity);  
  578.                 return null;  
  579.             }  
  580.         });  
  581.     }  
  582.   
  583.     public Object merge(final Object entity) throws DataAccessException {  
  584.         return executeWithNativeSession(new HibernateCallback() {  
  585.             public Object doInHibernate(Session session) throws HibernateException {  
  586.                 checkWriteOperationAllowed(session);  
  587.                 return session.merge(entity);  
  588.             }  
  589.         });  
  590.     }  
  591.   
  592.     public Object merge(final String entityName, final Object entity) throws DataAccessException {  
  593.         return executeWithNativeSession(new HibernateCallback() {  
  594.             public Object doInHibernate(Session session) throws HibernateException {  
  595.                 checkWriteOperationAllowed(session);  
  596.                 return session.merge(entityName, entity);  
  597.             }  
  598.         });  
  599.     }  
  600.   
  601.     public void delete(Object entity) throws DataAccessException {  
  602.         delete(entity, null);  
  603.     }  
  604.   
  605.     public void delete(final Object entity, final LockMode lockMode) throws DataAccessException {  
  606.         executeWithNativeSession(new HibernateCallback() {  
  607.             public Object doInHibernate(Session session) throws HibernateException {  
  608.                 checkWriteOperationAllowed(session);  
  609.                 if (lockMode != null) {  
  610.                     session.lock(entity, lockMode);  
  611.                 }  
  612.                 session.delete(entity);  
  613.                 return null;  
  614.             }  
  615.         });  
  616.     }  
  617.   
  618.     public void delete(String entityName, Object entity) throws DataAccessException {  
  619.         delete(entityName, entity, null);  
  620.     }  
  621.   
  622.     public void delete(final String entityName, final Object entity, final LockMode lockMode)  
  623.             throws DataAccessException {  
  624.   
  625.         executeWithNativeSession(new HibernateCallback() {  
  626.             public Object doInHibernate(Session session) throws HibernateException {  
  627.                 checkWriteOperationAllowed(session);  
  628.                 if (lockMode != null) {  
  629.                     session.lock(entityName, entity, lockMode);  
  630.                 }  
  631.                 session.delete(entityName, entity);  
  632.                 return null;  
  633.             }  
  634.         });  
  635.     }  
  636.   
  637.     public void deleteAll(final Collection entities) throws DataAccessException {  
  638.         executeWithNativeSession(new HibernateCallback() {  
  639.             public Object doInHibernate(Session session) throws HibernateException {  
  640.                 checkWriteOperationAllowed(session);  
  641.                 for (Iterator it = entities.iterator(); it.hasNext();) {  
  642.                     session.delete(it.next());  
  643.                 }  
  644.                 return null;  
  645.             }  
  646.         });  
  647.     }  
  648.   
  649.     public void flush() throws DataAccessException {  
  650.         executeWithNativeSession(new HibernateCallback() {  
  651.             public Object doInHibernate(Session session) throws HibernateException {  
  652.                 session.flush();  
  653.                 return null;  
  654.             }  
  655.         });  
  656.     }  
  657.   
  658.     public void clear() throws DataAccessException {  
  659.         executeWithNativeSession(new HibernateCallback() {  
  660.             public Object doInHibernate(Session session) {  
  661.                 session.clear();  
  662.                 return null;  
  663.             }  
  664.         });  
  665.     }  
  666.   
  667.   
  668.     //-------------------------------------------------------------------------  
  669.     // Convenience finder methods for HQL strings  
  670.     //-------------------------------------------------------------------------  
  671.   
  672.     public List find(String queryString) throws DataAccessException {  
  673.         return find(queryString, (Object[]) null);  
  674.     }  
  675.   
  676.     public List find(String queryString, Object value) throws DataAccessException {  
  677.         return find(queryString, new Object[] {value});  
  678.     }  
  679.   
  680.     public List find(final String queryString, final Object[] values) throws DataAccessException {  
  681.         return (List) executeWithNativeSession(new HibernateCallback() {  
  682.             public Object doInHibernate(Session session) throws HibernateException {  
  683.                 Query queryObject = session.createQuery(queryString);  
  684.                 prepareQuery(queryObject);  
  685.                 if (values != null) {  
  686.                     for (int i = 0; i < values.length; i++) {  
  687.                         queryObject.setParameter(i, values[i]);  
  688.                     }  
  689.                 }  
  690.                 return queryObject.list();  
  691.             }  
  692.         });  
  693.     }  
  694.   
  695.     public List findByNamedParam(String queryString, String paramName, Object value)  
  696.             throws DataAccessException {  
  697.   
  698.         return findByNamedParam(queryString, new String[] {paramName}, new Object[] {value});  
  699.     }  
  700.   
  701.     public List findByNamedParam(final String queryString, final String[] paramNames, final Object[] values)  
  702.             throws DataAccessException {  
  703.   
  704.         if (paramNames.length != values.length) {  
  705.             throw new IllegalArgumentException("Length of paramNames array must match length of values array");  
  706.         }  
  707.         return (List) executeWithNativeSession(new HibernateCallback() {  
  708.             public Object doInHibernate(Session session) throws HibernateException {  
  709.                 Query queryObject = session.createQuery(queryString);  
  710.                 prepareQuery(queryObject);  
  711.                 if (values != null) {  
  712.                     for (int i = 0; i < values.length; i++) {  
  713.                         applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);  
  714.                     }  
  715.                 }  
  716.                 return queryObject.list();  
  717.             }  
  718.         });  
  719.     }  
  720.   
  721.     public List findByValueBean(final String queryString, final Object valueBean)  
  722.             throws DataAccessException {  
  723.   
  724.         return (List) executeWithNativeSession(new HibernateCallback() {  
  725.             public Object doInHibernate(Session session) throws HibernateException {  
  726.                 Query queryObject = session.createQuery(queryString);  
  727.                 prepareQuery(queryObject);  
  728.                 queryObject.setProperties(valueBean);  
  729.                 return queryObject.list();  
  730.             }  
  731.         });  
  732.     }  
  733.   
  734.   
  735.     //-------------------------------------------------------------------------  
  736.     // Convenience finder methods for named queries  
  737.     //-------------------------------------------------------------------------  
  738.   
  739.     public List findByNamedQuery(String queryName) throws DataAccessException {  
  740.         return findByNamedQuery(queryName, (Object[]) null);  
  741.     }  
  742.   
  743.     public List findByNamedQuery(String queryName, Object value) throws DataAccessException {  
  744.         return findByNamedQuery(queryName, new Object[] {value});  
  745.     }  
  746.   
  747.     public List findByNamedQuery(final String queryName, final Object[] values) throws DataAccessException {  
  748.         return (List) executeWithNativeSession(new HibernateCallback() {  
  749.             public Object doInHibernate(Session session) throws HibernateException {  
  750.                 Query queryObject = session.getNamedQuery(queryName);  
  751.                 prepareQuery(queryObject);  
  752.                 if (values != null) {  
  753.                     for (int i = 0; i < values.length; i++) {  
  754.                         queryObject.setParameter(i, values[i]);  
  755.                     }  
  756.                 }  
  757.                 return queryObject.list();  
  758.             }  
  759.         });  
  760.     }  
  761.   
  762.     public List findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)  
  763.             throws DataAccessException {  
  764.   
  765.         return findByNamedQueryAndNamedParam(queryName, new String[] {paramName}, new Object[] {value});  
  766.     }  
  767.   
  768.     public List findByNamedQueryAndNamedParam(  
  769.             final String queryName, final String[] paramNames, final Object[] values)  
  770.             throws DataAccessException {  
  771.   
  772.         if (paramNames != null && values != null && paramNames.length != values.length) {  
  773.             throw new IllegalArgumentException("Length of paramNames array must match length of values array");  
  774.         }  
  775.         return (List) executeWithNativeSession(new HibernateCallback() {  
  776.             public Object doInHibernate(Session session) throws HibernateException {  
  777.                 Query queryObject = session.getNamedQuery(queryName);  
  778.                 prepareQuery(queryObject);  
  779.                 if (values != null) {  
  780.                     for (int i = 0; i < values.length; i++) {  
  781.                         applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);  
  782.                     }  
  783.                 }  
  784.                 return queryObject.list();  
  785.             }  
  786.         });  
  787.     }  
  788.   
  789.     public List findByNamedQueryAndValueBean(final String queryName, final Object valueBean)  
  790.             throws DataAccessException {  
  791.   
  792.         return (List) executeWithNativeSession(new HibernateCallback() {  
  793.             public Object doInHibernate(Session session) throws HibernateException {  
  794.                 Query queryObject = session.getNamedQuery(queryName);  
  795.                 prepareQuery(queryObject);  
  796.                 queryObject.setProperties(valueBean);  
  797.                 return queryObject.list();  
  798.             }  
  799.         });  
  800.     }  
  801.   
  802.   
  803.     //-------------------------------------------------------------------------  
  804.     // Convenience finder methods for detached criteria  
  805.     //-------------------------------------------------------------------------  
  806.   
  807.     public List findByCriteria(DetachedCriteria criteria) throws DataAccessException {  
  808.         return findByCriteria(criteria, -1, -1);  
  809.     }  
  810.   
  811.     public List findByCriteria(final DetachedCriteria criteria, final int firstResult, final int maxResults)  
  812.             throws DataAccessException {  
  813.   
  814.         Assert.notNull(criteria, "DetachedCriteria must not be null");  
  815.         return (List) executeWithNativeSession(new HibernateCallback() {  
  816.             public Object doInHibernate(Session session) throws HibernateException {  
  817.                 Criteria executableCriteria = criteria.getExecutableCriteria(session);  
  818.                 prepareCriteria(executableCriteria);  
  819.                 if (firstResult >= 0) {  
  820.                     executableCriteria.setFirstResult(firstResult);  
  821.                 }  
  822.                 if (maxResults > 0) {  
  823.                     executableCriteria.setMaxResults(maxResults);  
  824.                 }  
  825.                 return executableCriteria.list();  
  826.             }  
  827.         });  
  828.     }  
  829.   
  830.     public List findByExample(Object exampleEntity) throws DataAccessException {  
  831.         return findByExample(null, exampleEntity, -1, -1);  
  832.     }  
  833.   
  834.     public List findByExample(String entityName, Object exampleEntity) throws DataAccessException {  
  835.         return findByExample(entityName, exampleEntity, -1, -1);  
  836.     }  
  837.   
  838.     public List findByExample(Object exampleEntity, int firstResult, int maxResults) throws DataAccessException {  
  839.         return findByExample(null, exampleEntity, firstResult, maxResults);  
  840.     }  
  841.   
  842.     public List findByExample(  
  843.             final String entityName, final Object exampleEntity, final int firstResult, final int maxResults)  
  844.             throws DataAccessException {  
  845.   
  846.         Assert.notNull(exampleEntity, "Example entity must not be null");  
  847.         return (List) executeWithNativeSession(new HibernateCallback() {  
  848.             public Object doInHibernate(Session session) throws HibernateException {  
  849.                 Criteria executableCriteria = (entityName != null ?  
  850.                         session.createCriteria(entityName) : session.createCriteria(exampleEntity.getClass()));  
  851.                 executableCriteria.add(Example.create(exampleEntity));  
  852.                 prepareCriteria(executableCriteria);  
  853.                 if (firstResult >= 0) {  
  854.                     executableCriteria.setFirstResult(firstResult);  
  855.                 }  
  856.                 if (maxResults > 0) {  
  857.                     executableCriteria.setMaxResults(maxResults);  
  858.                 }  
  859.                 return executableCriteria.list();  
  860.             }  
  861.         });  
  862.     }  
  863.   
  864.   
  865.     //-------------------------------------------------------------------------  
  866.     // Convenience query methods for iteration and bulk updates/deletes  
  867.     //-------------------------------------------------------------------------  
  868.   
  869.     public Iterator iterate(String queryString) throws DataAccessException {  
  870.         return iterate(queryString, (Object[]) null);  
  871.     }  
  872.   
  873.     public Iterator iterate(String queryString, Object value) throws DataAccessException {  
  874.         return iterate(queryString, new Object[] {value});  
  875.     }  
  876.   
  877.     public Iterator iterate(final String queryString, final Object[] values) throws DataAccessException {  
  878.         return (Iterator) executeWithNativeSession(new HibernateCallback() {  
  879.             public Object doInHibernate(Session session) throws HibernateException {  
  880.                 Query queryObject = session.createQuery(queryString);  
  881.                 prepareQuery(queryObject);  
  882.                 if (values != null) {  
  883.                     for (int i = 0; i < values.length; i++) {  
  884.                         queryObject.setParameter(i, values[i]);  
  885.                     }  
  886.                 }  
  887.                 return queryObject.iterate();  
  888.             }  
  889.         });  
  890.     }  
  891.   
  892.     public void closeIterator(Iterator it) throws DataAccessException {  
  893.         try {  
  894.             Hibernate.close(it);  
  895.         }  
  896.         catch (HibernateException ex) {  
  897.             throw SessionFactoryUtils.convertHibernateAccessException(ex);  
  898.         }  
  899.     }  
  900.   
  901.     public int bulkUpdate(String queryString) throws DataAccessException {  
  902.         return bulkUpdate(queryString, (Object[]) null);  
  903.     }  
  904.   
  905.     public int bulkUpdate(String queryString, Object value) throws DataAccessException {  
  906.         return bulkUpdate(queryString, new Object[] {value});  
  907.     }  
  908.   
  909.     public int bulkUpdate(final String queryString, final Object[] values) throws DataAccessException {  
  910.         Integer updateCount = (Integer) executeWithNativeSession(new HibernateCallback() {  
  911.             public Object doInHibernate(Session session) throws HibernateException {  
  912.                 Query queryObject = session.createQuery(queryString);  
  913.                 prepareQuery(queryObject);  
  914.                 if (values != null) {  
  915.                     for (int i = 0; i < values.length; i++) {  
  916.                         queryObject.setParameter(i, values[i]);  
  917.                     }  
  918.                 }  
  919.                 return new Integer(queryObject.executeUpdate());  
  920.             }  
  921.         });  
  922.         return updateCount.intValue();  
  923.     }  
  924.   
  925.   
  926.     //-------------------------------------------------------------------------  
  927.     // Helper methods used by the operations above  
  928.     //-------------------------------------------------------------------------  
  929.   
  930.       
  931.     protected void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException {  
  932.         if (isCheckWriteOperations() && getFlushMode() != FLUSH_EAGER &&  
  933.                 session.getFlushMode().lessThan(FlushMode.COMMIT)) {  
  934.             throw new InvalidDataAccessApiUsageException(  
  935.                     "Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): "+  
  936.                     "Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.");  
  937.         }  
  938.     }  
  939.   
  940.       
  941.     protected void prepareQuery(Query queryObject) {  
  942.         if (isCacheQueries()) {  
  943.             queryObject.setCacheable(true);  
  944.             if (getQueryCacheRegion() != null) {  
  945.                 queryObject.setCacheRegion(getQueryCacheRegion());  
  946.             }  
  947.         }  
  948.         if (getFetchSize() > 0) {  
  949.             queryObject.setFetchSize(getFetchSize());  
  950.         }  
  951.         if (getMaxResults() > 0) {  
  952.             queryObject.setMaxResults(getMaxResults());  
  953.         }  
  954.         SessionFactoryUtils.applyTransactionTimeout(queryObject, getSessionFactory());  
  955.     }  
  956.   
  957.       
  958.     protected void prepareCriteria(Criteria criteria) {  
  959.         if (isCacheQueries()) {  
  960.             criteria.setCacheable(true);  
  961.             if (getQueryCacheRegion() != null) {  
  962.                 criteria.setCacheRegion(getQueryCacheRegion());  
  963.             }  
  964.         }  
  965.         if (getFetchSize() > 0) {  
  966.             criteria.setFetchSize(getFetchSize());  
  967.         }  
  968.         if (getMaxResults() > 0) {  
  969.             criteria.setMaxResults(getMaxResults());  
  970.         }  
  971.         SessionFactoryUtils.applyTransactionTimeout(criteria, getSessionFactory());  
  972.     }  
  973.   
  974.       
  975.     protected void applyNamedParameterToQuery(Query queryObject, String paramName, Object value)  
  976.             throws HibernateException {  
  977.   
  978.         if (value instanceof Collection) {  
  979.             queryObject.setParameterList(paramName, (Collection) value);  
  980.         }  
  981.         else if (value instanceof Object[]) {  
  982.             queryObject.setParameterList(paramName, (Object[]) value);  
  983.         }  
  984.         else {  
  985.             queryObject.setParameter(paramName, value);  
  986.         }  
  987.     }  
  988.   
  989.   
  990.       
  991.     private class CloseSuppressingInvocationHandler implements InvocationHandler {  
  992.   
  993.         private final Session target;  
  994.   
  995.         public CloseSuppressingInvocationHandler(Session target) {  
  996.             this.target = target;  
  997.         }  
  998.   
  999.         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  1000.             // Invocation on Session interface coming in...  
  1001.   
  1002.             if (method.getName().equals("equals")) {  
  1003.                 // Only consider equal when proxies are identical.  
  1004.                 return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);  
  1005.             }  
  1006.             else if (method.getName().equals("hashCode")) {  
  1007.                 // Use hashCode of Session proxy.  
  1008.                 return new Integer(hashCode());  
  1009.             }  
  1010.             else if (method.getName().equals("close")) {  
  1011.                 // Handle close method: suppress, not valid.  
  1012.                 return null;  
  1013.             }  
  1014.   
  1015.             // Invoke method on target Session.  
  1016.             try {  
  1017.                 Object retVal = method.invoke(this.target, args);  
  1018.   
  1019.                 // If return value is a Query or Criteria, apply transaction timeout.  
  1020.                 // Applies to createQuery, getNamedQuery, createCriteria.  
  1021.                 if (retVal instanceof Query) {  
  1022.                     prepareQuery(((Query) retVal));  
  1023.                 }  
  1024.                 if (retVal instanceof Criteria) {  
  1025.                     prepareCriteria(((Criteria) retVal));  
  1026.                 }  
  1027.   
  1028.                 return retVal;  
  1029.             }  
  1030.             catch (InvocationTargetException ex) {  
  1031.                 throw ex.getTargetException();  
  1032.             }  
  1033.         }  
  1034.     }  
  1035.   
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics