Java 类org.hibernate.CacheMode 实例源码

项目:lams    文件:QueryBinder.java   
private static CacheMode getCacheMode(CacheModeType cacheModeType) {
    switch ( cacheModeType ) {
        case GET:
            return CacheMode.GET;
        case IGNORE:
            return CacheMode.IGNORE;
        case NORMAL:
            return CacheMode.NORMAL;
        case PUT:
            return CacheMode.PUT;
        case REFRESH:
            return CacheMode.REFRESH;
        default:
            throw new AssertionFailure( "Unknown cacheModeType: " + cacheModeType );
    }
}
项目:lams    文件:QueryBinder.java   
private static CacheMode getCacheMode(AnnotationInstance[] hints, String element, String query) {
    String val = getString( hints, element );
    if ( val == null ) {
        return null;
    }
    if ( val.equalsIgnoreCase( CacheMode.GET.toString() ) ) {
        return CacheMode.GET;
    }
    if ( val.equalsIgnoreCase( CacheMode.IGNORE.toString() ) ) {
        return CacheMode.IGNORE;
    }
    if ( val.equalsIgnoreCase( CacheMode.NORMAL.toString() ) ) {
        return CacheMode.NORMAL;
    }
    if ( val.equalsIgnoreCase( CacheMode.PUT.toString() ) ) {
        return CacheMode.PUT;
    }
    if ( val.equalsIgnoreCase( CacheMode.REFRESH.toString() ) ) {
        return CacheMode.REFRESH;
    }
    throw new AnnotationException( "Unknown CacheMode in hint: " + query + ":" + element );
}
项目:lams    文件:DefaultDeleteEventListener.java   
protected void cascadeBeforeDelete(
        EventSource session,
        EntityPersister persister,
        Object entity,
        EntityEntry entityEntry,
        Set transientEntities) throws HibernateException {

    CacheMode cacheMode = session.getCacheMode();
    session.setCacheMode( CacheMode.GET );
    session.getPersistenceContext().incrementCascadeLevel();
    try {
        // cascade-delete to collections BEFORE the collection owner is deleted
        new Cascade( CascadingActions.DELETE, CascadePoint.AFTER_INSERT_BEFORE_DELETE, session ).cascade(
                persister,
                entity,
                transientEntities
        );
    }
    finally {
        session.getPersistenceContext().decrementCascadeLevel();
        session.setCacheMode( cacheMode );
    }
}
项目:lams    文件:DefaultDeleteEventListener.java   
protected void cascadeAfterDelete(
        EventSource session,
        EntityPersister persister,
        Object entity,
        Set transientEntities) throws HibernateException {

    CacheMode cacheMode = session.getCacheMode();
    session.setCacheMode( CacheMode.GET );
    session.getPersistenceContext().incrementCascadeLevel();
    try {
        // cascade-delete to many-to-one AFTER the parent was deleted
        new Cascade( CascadingActions.DELETE, CascadePoint.BEFORE_INSERT_AFTER_DELETE, session ).cascade(
                persister,
                entity,
                transientEntities
        );
    }
    finally {
        session.getPersistenceContext().decrementCascadeLevel();
        session.setCacheMode( cacheMode );
    }
}
项目:unitimes    文件:AbstractApiHelper.java   
public AbstractApiHelper(HttpServletRequest request, HttpServletResponse response, SessionContext context, CacheMode cacheMode) {
    iRequest = request;
    iResponse = response;
    iContext = context;
    iCacheMode = cacheMode;

    // select academic session if needed
    UserContext user = (iContext == null ? null : iContext.getUser());
    Long sessionId = getAcademicSessionId();
    if (user != null && sessionId != null && !sessionId.equals(user.getCurrentAcademicSessionId())) {
        String role = (user.getCurrentAuthority() == null ? null : user.getCurrentAuthority().getRole());
        if (getParameter("role") != null) role = getParameter("role");
        UserAuthority best = null;
        for (UserAuthority authority: user.getAuthorities()) {
            if (authority.getAcademicSession() != null && authority.getAcademicSession().getQualifierId().equals(sessionId)) {
                if (best == null || authority.getRole().equals(role)) best = authority;
            }
        }
        if (best != null) user.setCurrentAuthority(best);
    }
}
项目:unitimes    文件:InstructorSchedulingDatabaseLoader.java   
public void load() throws Exception {
    ApplicationProperties.setSessionId(iSessionId);
    org.hibernate.Session hibSession = null;
    Transaction tx = null;
    try {
        hibSession = TimetableManagerDAO.getInstance().createNewSession();
        hibSession.setCacheMode(CacheMode.IGNORE);
        hibSession.setFlushMode(FlushMode.COMMIT);

        tx = hibSession.beginTransaction(); 

        load(hibSession);

        tx.commit();
    } catch (Exception e) {
        iProgress.fatal("Unable to load input data, reason: " + e.getMessage(), e);
        tx.rollback();
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession != null && hibSession.isOpen()) hibSession.close();
    }
}
项目:unitimes    文件:TimetableDatabaseLoader.java   
public void load() {
    ApplicationProperties.setSessionId(iSessionId);
    org.hibernate.Session hibSession = null;
    Transaction tx = null;
    try {
        hibSession = TimetableManagerDAO.getInstance().getSession();
        hibSession.setCacheMode(CacheMode.IGNORE);
        hibSession.setFlushMode(FlushMode.COMMIT);

        tx = hibSession.beginTransaction(); 

        load(hibSession);

        tx.commit();
    } catch (Exception e) {
        iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load input data, reason:"+e.getMessage(),e);
        tx.rollback();
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession!=null && hibSession.isOpen()) hibSession.close();
    }
}
项目:cacheonix-core    文件:NamedQueryDefinition.java   
public NamedQueryDefinition(
        String query,
        boolean cacheable,
        String cacheRegion,
        Integer timeout,
        Integer fetchSize,
        FlushMode flushMode,
        CacheMode cacheMode,
        boolean readOnly,
        String comment,
        Map parameterTypes
) {
    this.query = query;
    this.cacheable = cacheable;
    this.cacheRegion = cacheRegion;
    this.timeout = timeout;
    this.fetchSize = fetchSize;
    this.flushMode = flushMode;
    this.parameterTypes = parameterTypes;
    this.cacheMode = cacheMode;
    this.readOnly = readOnly;
    this.comment = comment;
}
项目:cacheonix-core    文件:DefaultDeleteEventListener.java   
protected void cascadeBeforeDelete(
        EventSource session,
        EntityPersister persister,
        Object entity,
        EntityEntry entityEntry,
        Set transientEntities) throws HibernateException {

    CacheMode cacheMode = session.getCacheMode();
    session.setCacheMode( CacheMode.GET );
    session.getPersistenceContext().incrementCascadeLevel();
    try {
        // cascade-delete to collections BEFORE the collection owner is deleted
        new Cascade( CascadingAction.DELETE, Cascade.AFTER_INSERT_BEFORE_DELETE, session )
                .cascade( persister, entity, transientEntities );
    }
    finally {
        session.getPersistenceContext().decrementCascadeLevel();
        session.setCacheMode( cacheMode );
    }
}
项目:cacheonix-core    文件:DefaultDeleteEventListener.java   
protected void cascadeAfterDelete(
        EventSource session,
        EntityPersister persister,
        Object entity,
        Set transientEntities) throws HibernateException {

    CacheMode cacheMode = session.getCacheMode();
    session.setCacheMode( CacheMode.GET );
    session.getPersistenceContext().incrementCascadeLevel();
    try {
        // cascade-delete to many-to-one AFTER the parent was deleted
        new Cascade( CascadingAction.DELETE, Cascade.BEFORE_INSERT_AFTER_DELETE, session )
                .cascade( persister, entity, transientEntities );
    }
    finally {
        session.getPersistenceContext().decrementCascadeLevel();
        session.setCacheMode( cacheMode );
    }
}
项目:owsi-core-parent    文件:HibernateSearchDaoImpl.java   
protected void reindexClasses(FullTextEntityManager fullTextEntityManager, Set<Class<?>> entityClasses)
        throws InterruptedException {
    int batchSize = propertyService.get(HIBERNATE_SEARCH_REINDEX_BATCH_SIZE);
    int loadThreads = propertyService.get(HIBERNATE_SEARCH_REINDEX_LOAD_THREADS);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Targets for indexing job: {}", entityClasses);
    }

    for (Class<?> clazz : entityClasses) {
        ProgressMonitor progressMonitor = new ProgressMonitor();
        Thread t = new Thread(progressMonitor);
        LOGGER.info(String.format("Reindexing %1$s.", clazz));
        t.start();
        MassIndexer indexer = fullTextEntityManager.createIndexer(clazz);
        indexer.batchSizeToLoadObjects(batchSize)
                .threadsToLoadObjects(loadThreads)
                .cacheMode(CacheMode.NORMAL)
                .progressMonitor(progressMonitor)
                .startAndWait();
        progressMonitor.stop();
        t.interrupt();
        LOGGER.info(String.format("Reindexing %1$s done.", clazz));
    }
}
项目:sakai    文件:ProfileDaoImpl.java   
/**
     * {@inheritDoc}
     */
public List<UserProfile> getUserProfiles(final int start, final int count) {

    //get fields directly from the sakaiperson table and use Transformers.aliasToBean to transform into UserProfile pojo
    //the idea is we *dont* want a SakaiPerson object
    HibernateCallback<List<UserProfile>> hcb = session -> {
           Query q = session.getNamedQuery(QUERY_GET_SAKAI_PERSON);
           //see scalars in the hbm
           q.setFirstResult(start);
           q.setMaxResults(count);
           q.setResultTransformer(Transformers.aliasToBean(UserProfile.class));
           q.setCacheMode(CacheMode.GET);
           return q.list();
       };

    return getHibernateTemplate().execute(hcb);
}
项目:unitime    文件:AbstractApiHelper.java   
public AbstractApiHelper(HttpServletRequest request, HttpServletResponse response, SessionContext context, CacheMode cacheMode) {
    iRequest = request;
    iResponse = response;
    iContext = context;
    iCacheMode = cacheMode;

    // select academic session if needed
    UserContext user = (iContext == null ? null : iContext.getUser());
    Long sessionId = getAcademicSessionId();
    if (user != null && sessionId != null && !sessionId.equals(user.getCurrentAcademicSessionId())) {
        String role = (user.getCurrentAuthority() == null ? null : user.getCurrentAuthority().getRole());
        if (getParameter("role") != null) role = getParameter("role");
        UserAuthority best = null;
        for (UserAuthority authority: user.getAuthorities()) {
            if (authority.getAcademicSession() != null && authority.getAcademicSession().getQualifierId().equals(sessionId)) {
                if (best == null || authority.getRole().equals(role)) best = authority;
            }
        }
        if (best != null) user.setCurrentAuthority(best);
    }
}
项目:unitime    文件:InstructorSchedulingDatabaseLoader.java   
public void load() throws Exception {
    ApplicationProperties.setSessionId(iSessionId);
    org.hibernate.Session hibSession = null;
    Transaction tx = null;
    try {
        hibSession = TimetableManagerDAO.getInstance().createNewSession();
        hibSession.setCacheMode(CacheMode.IGNORE);
        hibSession.setFlushMode(FlushMode.COMMIT);

        tx = hibSession.beginTransaction(); 

        load(hibSession);

        tx.commit();
    } catch (Exception e) {
        iProgress.fatal("Unable to load input data, reason: " + e.getMessage(), e);
        tx.rollback();
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession != null && hibSession.isOpen()) hibSession.close();
    }
}
项目:unitime    文件:TimetableDatabaseLoader.java   
public void load() {
    ApplicationProperties.setSessionId(iSessionId);
    org.hibernate.Session hibSession = null;
    Transaction tx = null;
    try {
        hibSession = TimetableManagerDAO.getInstance().getSession();
        hibSession.setCacheMode(CacheMode.IGNORE);
        hibSession.setFlushMode(FlushMode.COMMIT);

        tx = hibSession.beginTransaction(); 

        load(hibSession);

        tx.commit();
    } catch (Exception e) {
        iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load input data, reason:"+e.getMessage(),e);
        tx.rollback();
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession!=null && hibSession.isOpen()) hibSession.close();
    }
}
项目:java-classic-playground    文件:Program.java   
private static void runStatefulHql() throws Exception {
  Stopwatch watch = Stopwatch.createStarted();
  Session session = sessionFactory.openSession();
  try {
    session.getTransaction().begin();
    @SuppressWarnings("unchecked")
    List<Driver> list = 
      session.createQuery("select d from Driver d LEFT JOIN FETCH d.cars c")
      .setCacheable(true)
      .setCacheMode(CacheMode.NORMAL).list();
    for (Driver entry : list) {
      LOG.info("Entry " + entry.getId());
    }
    session.getTransaction().commit();
  } catch (Exception ex) {
    session.getTransaction().rollback();
    throw ex;
  } finally {
    session.close();
  }
  LOG.info("StatefulHql:=" + watch.toString());
}
项目:java-classic-playground    文件:Program.java   
private static void runStatefulCriteria() throws Exception {
  Stopwatch watch = Stopwatch.createStarted();
  Session session = sessionFactory.openSession();
  try {
    session.getTransaction().begin();
    @SuppressWarnings("unchecked")
    List<Driver> list = 
      session
        .createCriteria(Driver.class)
        .setFetchMode("cars", FetchMode.JOIN)
        .setCacheable(true)
        .setCacheMode(CacheMode.NORMAL)
        .list();
    for (Driver entry : list) {
      LOG.info("Entry " + entry.getId());
    }
    session.getTransaction().commit();
  } catch (Exception ex) {
    session.getTransaction().rollback();
    throw ex;
  } finally {
    session.close();
  }
  LOG.info("StatefulCriteria:=" + watch.toString());
}
项目:sakai    文件:ProfileDaoImpl.java   
/**
     * {@inheritDoc}
     */
public List<UserProfile> getUserProfiles(final int start, final int count) {

    //get fields directly from the sakaiperson table and use Transformers.aliasToBean to transform into UserProfile pojo
    //the idea is we *dont* want a SakaiPerson object
    HibernateCallback<List<UserProfile>> hcb = session -> {
           Query q = session.getNamedQuery(QUERY_GET_SAKAI_PERSON);
           //see scalars in the hbm
           q.setFirstResult(start);
           q.setMaxResults(count);
           q.setResultTransformer(Transformers.aliasToBean(UserProfile.class));
           q.setCacheMode(CacheMode.GET);
           return q.list();
       };

    return getHibernateTemplate().execute(hcb);
}
项目:further-open-core    文件:HibernateCriteriaScrollableResultsExecutor.java   
/**
 * Execute Hibernate criteria query and return a scrollable result set.
 * 
 * @param criteria
 *            Hibernate criteria
 * @return scrollable result set
 * @see https://jira.chpc.utah.edu/browse/FUR-1274
 */
@HibernateExecutor
private ScrollableResults getResultListFromHibernate(final GenericCriteria criteria)
{
    ScrollableResults results = null;
    // Need to use INSENSITIVE scroll-mode per FUR-1300 and
    // http://www.coderanch.com/t/301684/JDBC/java/Unsupported-syntax-refreshRow
    final ScrollMode scrollMode = ScrollMode.SCROLL_INSENSITIVE;
    try
    {
        results = criteria.setCacheMode(CacheMode.IGNORE).scroll(scrollMode);
    }
    catch (final HibernateException e)
    {
        log.error("An exception occurred while scrolling results", e);
    }

    // Normally we won't know up-front the size of a streaming result set. But for
    // easier debugging of the subsequent paging sub-chain, print out the size of the
    // list because we know it already in this case.
    if (log.isDebugEnabled())
    {
        log.debug("Result set = " + StringUtil.getNullSafeToString(results));
    }
    return results;
}
项目:lams    文件:HbmBinder.java   
private static void bindNamedQuery(Element queryElem, String path, Mappings mappings) {
    String queryName = queryElem.attributeValue( "name" );
    if (path!=null) queryName = path + '.' + queryName;
    String query = queryElem.getText();
    LOG.debugf( "Named query: %s -> %s", queryName, query );

    boolean cacheable = "true".equals( queryElem.attributeValue( "cacheable" ) );
    String region = queryElem.attributeValue( "cache-region" );
    Attribute tAtt = queryElem.attribute( "timeout" );
    Integer timeout = tAtt == null ? null : Integer.valueOf( tAtt.getValue() );
    Attribute fsAtt = queryElem.attribute( "fetch-size" );
    Integer fetchSize = fsAtt == null ? null : Integer.valueOf( fsAtt.getValue() );
    Attribute roAttr = queryElem.attribute( "read-only" );
    boolean readOnly = roAttr != null && "true".equals( roAttr.getValue() );
    Attribute cacheModeAtt = queryElem.attribute( "cache-mode" );
    String cacheMode = cacheModeAtt == null ? null : cacheModeAtt.getValue();
    Attribute cmAtt = queryElem.attribute( "comment" );
    String comment = cmAtt == null ? null : cmAtt.getValue();

    NamedQueryDefinition namedQuery = new NamedQueryDefinitionBuilder().setName( queryName )
            .setQuery( query )
            .setCacheable( cacheable )
            .setCacheRegion( region )
            .setTimeout( timeout )
            .setFetchSize( fetchSize )
            .setFlushMode( FlushMode.interpretExternalSetting( queryElem.attributeValue( "flush-mode" ) ) )
            .setCacheMode( CacheMode.interpretExternalSetting( cacheMode ) )
            .setReadOnly( readOnly )
            .setComment( comment )
            .setParameterTypes( getParameterTypes( queryElem ) )
            .createNamedQueryDefinition();

    mappings.addQuery( namedQuery.getName(), namedQuery );
}
项目:lams    文件:QueryHintDefinition.java   
public CacheMode getCacheMode(String query) {
    String hitName = QueryHints.CACHE_MODE;
    String value =(String) hintsMap.get( hitName );
    if ( value == null ) {
        return null;
    }
    try {
        return CacheMode.interpretExternalSetting( value );
    }
    catch ( MappingException e ) {
        throw new AnnotationException( "Unknown CacheMode in hint: " + query + ":" + hitName, e );
    }
}
项目:lams    文件:NamedSQLQueryDefinition.java   
/**
 * This form was initially used to construct a NamedSQLQueryDefinition from the binder code when a the
 * result-set mapping information is not explicitly  provided in the query definition
 * (i.e., no resultset-mapping used).
 *
 * @param name The name of named query
 * @param query The sql query string
 * @param queryReturns The in-lined query return definitions
 * @param querySpaces Any specified query spaces (used for auto-flushing)
 * @param cacheable Whether the query results are cacheable
 * @param cacheRegion If cacheable, the region into which to store the results
 * @param timeout A JDBC-level timeout to be applied
 * @param fetchSize A JDBC-level fetch-size to be applied
 * @param flushMode The flush mode to use for this query
 * @param cacheMode The cache mode to use during execution and subsequent result loading
 * @param readOnly Whether returned entities should be marked as read-only in the session
 * @param comment Any sql comment to be applied to the query
 * @param parameterTypes parameter type map
 * @param callable Does the query string represent a callable object (i.e., proc)
 *
 * @deprecated Use {@link NamedSQLQueryDefinitionBuilder} instead.
 */
@Deprecated
public NamedSQLQueryDefinition(
        String name,
        String query,
        NativeSQLQueryReturn[] queryReturns,
        List<String> querySpaces,
        boolean cacheable,
        String cacheRegion,
        Integer timeout,
        Integer fetchSize,
        FlushMode flushMode,
        CacheMode cacheMode,
        boolean readOnly,
        String comment,
        Map parameterTypes,
        boolean callable) {
    this(
            name,
            query,
            cacheable,
            cacheRegion,
            timeout,
            fetchSize,
            flushMode,
            cacheMode,
            readOnly,
            comment,
            parameterTypes,
            null,       // firstResult
            null,       // maxResults
            null,       // resultSetRef
            querySpaces,
            callable,
            queryReturns
    );
}
项目:lams    文件:NamedSQLQueryDefinition.java   
/**
 * This form was initially used to construct a NamedSQLQueryDefinition from the binder code when a
 * resultset-mapping reference is used.
 *
 * @param name The name of named query
 * @param query The sql query string
 * @param resultSetRef The resultset-mapping name
 * @param querySpaces Any specified query spaces (used for auto-flushing)
 * @param cacheable Whether the query results are cacheable
 * @param cacheRegion If cacheable, the region into which to store the results
 * @param timeout A JDBC-level timeout to be applied
 * @param fetchSize A JDBC-level fetch-size to be applied
 * @param flushMode The flush mode to use for this query
 * @param cacheMode The cache mode to use during execution and subsequent result loading
 * @param readOnly Whether returned entities should be marked as read-only in the session
 * @param comment Any sql comment to be applied to the query
 * @param parameterTypes parameter type map
 * @param callable Does the query string represent a callable object (i.e., proc)
 *
 * @deprecated Use {@link NamedSQLQueryDefinitionBuilder} instead.
 */
@Deprecated
public NamedSQLQueryDefinition(
        String name,
        String query,
        String resultSetRef,
        List<String> querySpaces,
        boolean cacheable,
        String cacheRegion,
        Integer timeout,
        Integer fetchSize,
        FlushMode flushMode,
        CacheMode cacheMode,
        boolean readOnly,
        String comment,
        Map parameterTypes,
        boolean callable) {

    this(
            name,
            query,
            cacheable,
            cacheRegion,
            timeout,
            fetchSize,
            flushMode,
            cacheMode,
            readOnly,
            comment,
            parameterTypes,
            null,       // firstResult
            null,       // maxResults
            resultSetRef,
            querySpaces,
            callable,
            null        // queryReturns
    );
}
项目:lams    文件:NamedSQLQueryDefinition.java   
NamedSQLQueryDefinition(
        String name,
        String query,
        boolean cacheable,
        String cacheRegion,
        Integer timeout,
        Integer fetchSize,
        FlushMode flushMode,
        CacheMode cacheMode,
        boolean readOnly,
        String comment,
        Map parameterTypes,
        Integer firstResult,
        Integer maxResults,
        String resultSetRef,
        List<String> querySpaces,
        boolean callable,
        NativeSQLQueryReturn[] queryReturns) {
    super(
            name,
            query.trim(), /* trim done to workaround stupid oracle bug that cant handle whitespaces before a { in a sp */
            cacheable,
            cacheRegion,
            timeout,
            null,       // lockOptions
            fetchSize,
            flushMode,
            cacheMode,
            readOnly,
            comment,
            parameterTypes,
            firstResult,
            maxResults
    );
    this.resultSetRef = resultSetRef;
    this.querySpaces = querySpaces;
    this.callable = callable;
    this.queryReturns = queryReturns;
}
项目:lams    文件:NamedQueryDefinition.java   
/**
 * This form is used to bind named queries from Hibernate metadata, both {@code hbm.xml} files and
 * {@link org.hibernate.annotations.NamedQuery} annotation.
 *
 * @param name The name under which to key/register the query
 * @param query The query string.
 * @param cacheable Is the query cacheable?
 * @param cacheRegion If cacheable, was there a specific region named?
 * @param timeout Query timeout, {@code null} indicates no timeout
 * @param fetchSize Fetch size associated with the query, {@code null} indicates no limit
 * @param flushMode Flush mode associated with query
 * @param cacheMode Cache mode associated with query
 * @param readOnly Should entities returned from this query (those not already associated with the Session anyway)
 *      be loaded as read-only?
 * @param comment SQL comment to be used in the generated SQL, {@code null} indicates none
 * @param parameterTypes (no idea, afaict this is always passed as null)
 *
 * @deprecated Use {@link NamedQueryDefinitionBuilder} instead.
 */
@Deprecated
public NamedQueryDefinition(
        String name,
        String query,
        boolean cacheable,
        String cacheRegion,
        Integer timeout,
        Integer fetchSize,
        FlushMode flushMode,
        CacheMode cacheMode,
        boolean readOnly,
        String comment,
        Map parameterTypes) {
    this(
            name,
            query,
            cacheable,
            cacheRegion,
            timeout,
            LockOptions.WAIT_FOREVER,
            fetchSize,
            flushMode,
            cacheMode,
            readOnly,
            comment,
            parameterTypes
    );
}
项目:lams    文件:NamedQueryDefinition.java   
/**
 * This version is used to bind named queries defined via {@link javax.persistence.NamedQuery}.
 *
 * @param name The name under which to key/register the query
 * @param query The query string.
 * @param cacheable Is the query cacheable?
 * @param cacheRegion If cacheable, was there a specific region named?
 * @param timeout Query timeout, {@code null} indicates no timeout
 * @param lockTimeout Specifies the lock timeout for queries that apply lock modes.
 * @param fetchSize Fetch size associated with the query, {@code null} indicates no limit
 * @param flushMode Flush mode associated with query
 * @param cacheMode Cache mode associated with query
 * @param readOnly Should entities returned from this query (those not already associated with the Session anyway)
 *      be loaded as read-only?
 * @param comment SQL comment to be used in the generated SQL, {@code null} indicates none
 * @param parameterTypes (no idea, afaict this is always passed as null)
 *
 * @deprecated Use {@link NamedQueryDefinitionBuilder} instead.
 */
@Deprecated
public NamedQueryDefinition(
        String name,
        String query,
        boolean cacheable,
        String cacheRegion,
        Integer timeout,
        Integer lockTimeout,
        Integer fetchSize,
        FlushMode flushMode,
        CacheMode cacheMode,
        boolean readOnly,
        String comment,
        Map parameterTypes) {
    this(
            name,
            query,
            cacheable,
            cacheRegion,
            timeout,
            new LockOptions().setTimeOut( lockTimeout ),
            fetchSize,
            flushMode,
            cacheMode,
            readOnly,
            comment,
            parameterTypes,
            null,       // firstResult
            null        // maxResults
    );
}
项目:lams    文件:NamedQueryDefinition.java   
NamedQueryDefinition(
        String name,
        String query,
        boolean cacheable,
        String cacheRegion,
        Integer timeout,
        LockOptions lockOptions,
        Integer fetchSize,
        FlushMode flushMode,
        CacheMode cacheMode,
        boolean readOnly,
        String comment,
        Map parameterTypes,
        Integer firstResult,
        Integer maxResults) {
    this.name = name;
    this.query = query;
    this.cacheable = cacheable;
    this.cacheRegion = cacheRegion;
    this.timeout = timeout;
    this.lockOptions = lockOptions;
    this.fetchSize = fetchSize;
    this.flushMode = flushMode;
    this.parameterTypes = parameterTypes;
    this.cacheMode = cacheMode;
    this.readOnly = readOnly;
    this.comment = comment;

    this.firstResult = firstResult;
    this.maxResults = maxResults;
}
项目:lams    文件:TwoPhaseLoad.java   
private static boolean useMinimalPuts(SessionImplementor session, EntityEntry entityEntry) {
    return ( session.getFactory().getSettings().isMinimalPutsEnabled()
            && session.getCacheMode()!=CacheMode.REFRESH )
            || ( entityEntry.getPersister().hasLazyProperties()
            && entityEntry.isLoadedWithLazyPropertiesUnfetched()
            && entityEntry.getPersister().isLazyPropertiesCacheable() );
}
项目:lams    文件:SessionImpl.java   
@Override
public void setCacheMode(CacheMode cacheMode) {
    errorIfClosed();
    checkTransactionSynchStatus();
    LOG.tracev( "Setting cache mode to: {0}", cacheMode );
    this.cacheMode= cacheMode;
}
项目:lams    文件:SessionImpl.java   
/**
 * Used by JDK serialization...
 *
 * @param ois The input stream from which we are being read...
 * @throws IOException Indicates a general IO stream exception
 * @throws ClassNotFoundException Indicates a class resolution issue
 */
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
    LOG.trace( "Deserializing session" );

    ois.defaultReadObject();

    entityNameResolver = new CoordinatingEntityNameResolver();

    connectionReleaseMode = ConnectionReleaseMode.parse( ( String ) ois.readObject() );
    autoClear = ois.readBoolean();
    autoJoinTransactions = ois.readBoolean();
    flushMode = FlushMode.valueOf( ( String ) ois.readObject() );
    cacheMode = CacheMode.valueOf( ( String ) ois.readObject() );
    flushBeforeCompletionEnabled = ois.readBoolean();
    autoCloseSessionEnabled = ois.readBoolean();
    interceptor = ( Interceptor ) ois.readObject();

    factory = SessionFactoryImpl.deserialize( ois );
    sessionOwner = ( SessionOwner ) ois.readObject();

    transactionCoordinator = TransactionCoordinatorImpl.deserialize( ois, this );

    persistenceContext = StatefulPersistenceContext.deserialize( ois, this );
    actionQueue = ActionQueue.deserialize( ois, this );

    loadQueryInfluencers = (LoadQueryInfluencers) ois.readObject();

    // LoadQueryInfluencers.getEnabledFilters() tries to validate each enabled
    // filter, which will fail when called before FilterImpl.afterDeserialize( factory );
    // Instead lookup the filter by name and then call FilterImpl.afterDeserialize( factory ).
    for ( String filterName : loadQueryInfluencers.getEnabledFilterNames() ) {
        ((FilterImpl) loadQueryInfluencers.getEnabledFilter( filterName )).afterDeserialize( factory );
    }
}
项目:unitimes    文件:ExamDatabaseLoader.java   
public void load() throws Exception {
    ApplicationProperties.setSessionId(iSessionId);
    iProgress.setStatus("Loading input data ...");
    org.hibernate.Session hibSession = new ExamDAO().getSession();
    hibSession.setCacheMode(CacheMode.IGNORE);
    Transaction tx = null;
    try {
        tx = hibSession.beginTransaction();
        TravelTime.populateTravelTimes(getModel().getDistanceMetric(), iSessionId, hibSession);
        loadPeriods();
        loadRooms();

        RoomAvailabilityInterface availability = null;
        if (SolverServerImplementation.getInstance() != null)
            availability = SolverServerImplementation.getInstance().getRoomAvailability();
        else
            availability = RoomAvailability.getInstance();
        if (availability != null) loadRoomAvailability(availability);

        loadExams();
        loadStudents();
        loadDistributions();
        ExamType type = ExamTypeDAO.getInstance().get(iExamTypeId, hibSession);
        if (ApplicationProperty.ExaminationConsiderEventConflicts.isTrue(type.getReference())) loadAvailabilitiesFromEvents();
        if (ApplicationProperty.ExaminationCreateSameRoomConstraints.isTrue(type.getReference())) makeupSameRoomConstraints();
        getModel().init();
        getModel().clearAssignmentContexts(getAssignment());
        checkConsistency();
        assignInitial();
        tx.commit();
    } catch (Exception e) {
        iProgress.fatal("Unable to load examination problem, reason: "+e.getMessage(),e);
        if (tx!=null) tx.rollback();
        throw e;
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession!=null && hibSession.isOpen()) hibSession.close();
    }
}
项目:unitimes    文件:StudentSectioningDatabaseSaver.java   
public void save() {
    iProgress.setStatus("Saving solution ...");
    iTimeStamp = new Date();
    org.hibernate.Session hibSession = null;
    Transaction tx = null;
    try {
        hibSession = SessionDAO.getInstance().getSession();
        hibSession.setCacheMode(CacheMode.IGNORE);
        hibSession.setFlushMode(FlushMode.MANUAL);

        tx = hibSession.beginTransaction(); 

        Session session = Session.getSessionUsingInitiativeYearTerm(iInitiative, iYear, iTerm);

        if (session==null) throw new Exception("Session "+iInitiative+" "+iTerm+iYear+" not found!");
        ApplicationProperties.setSessionId(session.getUniqueId());

        save(session, hibSession);

        StudentSectioningQueue.sessionStatusChanged(hibSession, null, session.getUniqueId(), true);

        hibSession.flush();

        tx.commit(); tx = null;

    } catch (Exception e) {
        iProgress.fatal("Unable to save student schedule, reason: "+e.getMessage(),e);
        sLog.error(e.getMessage(),e);
        if (tx != null) tx.rollback();
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession!=null && hibSession.isOpen()) hibSession.close();
    }
}
项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkApplicationListenerTest.java   
@Test
public void configuresTheSessionsCacheMode() throws Exception {
    this.prepareAppEvent("methodWithCacheModeIgnoreAnnotation");

    this.execute();

    verify(this.session).setCacheMode(CacheMode.IGNORE);
}
项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkApplicationListenerTest.java   
@UnitOfWork(
    readOnly = false,
    cacheMode = CacheMode.NORMAL,
    transactional = true,
    flushMode = FlushMode.AUTO)
public void methodWithDefaultAnnotation() {
}
项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkApplicationListenerTest.java   
@UnitOfWork(
    readOnly = true,
    cacheMode = CacheMode.NORMAL,
    transactional = true,
    flushMode = FlushMode.AUTO)
public void methodWithReadOnlyAnnotation() {
}
项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkApplicationListenerTest.java   
@UnitOfWork(
    readOnly = false,
    cacheMode = CacheMode.IGNORE,
    transactional = true,
    flushMode = FlushMode.AUTO)
public void methodWithCacheModeIgnoreAnnotation() {
}
项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkApplicationListenerTest.java   
@UnitOfWork(
    readOnly = false,
    cacheMode = CacheMode.NORMAL,
    transactional = true,
    flushMode = FlushMode.ALWAYS)
public void methodWithFlushModeAlwaysAnnotation() {
}
项目:CredentialStorageService-dw-hibernate    文件:UnitOfWorkApplicationListenerTest.java   
@UnitOfWork(
    readOnly = false,
    cacheMode = CacheMode.NORMAL,
    transactional = false,
    flushMode = FlushMode.AUTO)
public void methodWithTransactionalFalseAnnotation() {
}
项目:Discord-Streambot    文件:StreamDao.java   
public StreamEntity getByIdAndName(GuildEntity guild, String name){
    sessionFactory.getCurrentSession().beginTransaction();
    sessionFactory.getCurrentSession().setCacheMode(CacheMode.IGNORE);
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(StreamEntity.class);
    criteria.add(Restrictions.eq("guild", guild))
            .add(Restrictions.eq("channelName", name));
    sessionFactory.getCurrentSession().setCacheMode(CacheMode.IGNORE);
    return (StreamEntity) criteria.uniqueResult();
}
项目:communote-server    文件:UserDaoImpl.java   
@Override
protected void handleResetTermsAccepted(final Long userIdToIgnore) {
    // Note: not using bulk updates as it will delete the entire UserCache region which is
    // especially bad for SaaS because all clients are in the same region
    getHibernateTemplate().executeWithNativeSession(new HibernateCallback<Object>() {
        @Override
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session
                    .createQuery("from " + UserConstants.CLASS_NAME + " where "
                            + UserConstants.TERMSACCEPTED + " = ? AND (" + UserConstants.STATUS
                            + "= ? OR " + UserConstants.STATUS + "= ?) AND "
                            + CommunoteEntityConstants.ID + " != ?")
                    .setParameter(0, Boolean.TRUE).setParameter(1, UserStatus.ACTIVE)
                    .setParameter(2, UserStatus.TEMPORARILY_DISABLED)
                    .setParameter(3, userIdToIgnore);
            query.setCacheMode(CacheMode.GET);
            Iterator iterator = query.iterate();
            int count = 0;
            while (iterator.hasNext()) {
                User user = (User) iterator.next();
                user.setTermsAccepted(false);
                // avoid out of memory by flushing session cache
                if (++count % 40 == 0) {
                    session.flush();
                    session.clear();
                }
            }
            return null;
        }
    });
}