下面列出了org.hibernate.search.mapper.orm.session.SearchSession#org.hibernate.CacheMode 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
/**
* {@inheritDoc}
*/
@Override
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
final HibernateCallback<List<UserProfile>> hcb = session -> {
final 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);
}
@Test
public void test_hql_api_basic_usage_example() {
doInJPA( this::entityManagerFactory, entityManager -> {
Session session = entityManager.unwrap( Session.class );
//tag::hql-api-basic-usage-example[]
org.hibernate.query.Query query = session.createQuery(
"select p " +
"from Person p " +
"where p.name like :name" )
// timeout - in seconds
.setTimeout( 2 )
// write to L2 caches, but do not read from them
.setCacheMode( CacheMode.REFRESH )
// assuming query cache was enabled for the SessionFactory
.setCacheable( true )
// add a comment to the generated SQL if enabled via the hibernate.use_sql_comments configuration property
.setComment( "+ INDEX(p idx_person_name)" );
//end::hql-api-basic-usage-example[]
});
}
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();
}
}
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;
}
@Override
public final T getReference(Serializable id) {
CacheMode sessionCacheMode = getCacheMode();
boolean cacheModeChanged = false;
if ( cacheMode != null ) {
// naive check for now...
// todo : account for "conceptually equal"
if ( cacheMode != sessionCacheMode ) {
setCacheMode( cacheMode );
cacheModeChanged = true;
}
}
try {
return doGetReference( id );
}
finally {
if ( cacheModeChanged ) {
// change it back
setCacheMode( sessionCacheMode );
}
}
}
@Override
@SuppressWarnings("unchecked")
public <K extends Serializable> List<T> multiLoad(K... ids) {
CacheMode sessionCacheMode = getCacheMode();
boolean cacheModeChanged = false;
if ( cacheMode != null ) {
// naive check for now...
// todo : account for "conceptually equal"
if ( cacheMode != sessionCacheMode ) {
setCacheMode( cacheMode );
cacheModeChanged = true;
}
}
try {
return entityPersister.multiLoad( ids, SessionImpl.this, this );
}
finally {
if ( cacheModeChanged ) {
// change it back
setCacheMode( sessionCacheMode );
}
}
}
@Override
@SuppressWarnings("unchecked")
public <K extends Serializable> List<T> multiLoad(List<K> ids) {
CacheMode sessionCacheMode = getCacheMode();
boolean cacheModeChanged = false;
if ( cacheMode != null ) {
// naive check for now...
// todo : account for "conceptually equal"
if ( cacheMode != sessionCacheMode ) {
setCacheMode( cacheMode );
cacheModeChanged = true;
}
}
try {
return entityPersister.multiLoad( ids.toArray( new Serializable[ ids.size() ] ), SessionImpl.this, this );
}
finally {
if ( cacheModeChanged ) {
// change it back
setCacheMode( sessionCacheMode );
}
}
}
private CacheMode determineAppropriateLocalCacheMode(Map<String, Object> localProperties) {
CacheRetrieveMode retrieveMode = null;
CacheStoreMode storeMode = null;
if ( localProperties != null ) {
retrieveMode = determineCacheRetrieveMode( localProperties );
storeMode = determineCacheStoreMode( localProperties );
}
if ( retrieveMode == null ) {
// use the EM setting
retrieveMode = determineCacheRetrieveMode( this.properties );
}
if ( storeMode == null ) {
// use the EM setting
storeMode = determineCacheStoreMode( this.properties );
}
return CacheModeHelper.interpretCacheMode( storeMode, retrieveMode );
}
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
Cascade.cascade(
CascadingActions.DELETE,
CascadePoint.AFTER_INSERT_BEFORE_DELETE,
session,
persister,
entity,
transientEntities
);
}
finally {
session.getPersistenceContext().decrementCascadeLevel();
session.setCacheMode( cacheMode );
}
}
/**
* Return {@link SystemParameter) resource and matches with the given id.
*
* @param credentials Injected by {@link RobeAuth} annotation for authentication.
* @param id This is the oid of {@link SystemParameter}
* @return {@link SystemParameter} resource matches with the given id.
*/
@RobeService(group = "SystemParameter", description = "Return SystemParameter resource.")
@Path("{id}")
@GET
@UnitOfWork(readOnly = true, cacheMode = CacheMode.GET, flushMode = FlushMode.MANUAL)
public SystemParameter get(@RobeAuth Credentials credentials, @PathParam("id") String id) {
SystemParameter entity = systemParameterDao.findById(id);
if (entity == null) {
throw new WebApplicationException(Response.status(404).build());
}
return entity;
}
public CompletionStage<List<T>> perform(Supplier<CompletionStage<List<T>>> executor) {
CacheMode sessionCacheMode = getCacheMode();
boolean cacheModeChanged = false;
if ( cacheMode != null ) {
// naive check for now...
// todo : account for "conceptually equal"
if ( cacheMode != sessionCacheMode ) {
setCacheMode( cacheMode );
cacheModeChanged = true;
}
}
if ( graphSemantic != null ) {
if ( rootGraph == null ) {
throw new IllegalArgumentException( "Graph semantic specified, but no RootGraph was supplied" );
}
getLoadQueryInfluencers().getEffectiveEntityGraph().applyGraph( rootGraph, graphSemantic );
}
boolean finalCacheModeChanged = cacheModeChanged;
return executor.get()
.whenComplete( (v, x) -> {
if ( graphSemantic != null ) {
getLoadQueryInfluencers().getEffectiveEntityGraph().clear();
}
if ( finalCacheModeChanged ) {
// change it back
setCacheMode( sessionCacheMode );
}
} );
}
public static CacheMode getCacheMode(String cacheMode) {
if (cacheMode == null) return null;
if ( "get".equals( cacheMode ) ) return CacheMode.GET;
if ( "ignore".equals( cacheMode ) ) return CacheMode.IGNORE;
if ( "normal".equals( cacheMode ) ) return CacheMode.NORMAL;
if ( "put".equals( cacheMode ) ) return CacheMode.PUT;
if ( "refresh".equals( cacheMode ) ) return CacheMode.REFRESH;
throw new MappingException("Unknown Cache Mode: " + cacheMode);
}
/**
* This form used to construct a NamedSQLQueryDefinition from the binder
* code when a resultset-mapping reference is used.
*
* @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)
*/
public NamedSQLQueryDefinition(
String query,
String resultSetRef,
List querySpaces,
boolean cacheable,
String cacheRegion,
Integer timeout,
Integer fetchSize,
FlushMode flushMode,
CacheMode cacheMode,
boolean readOnly,
String comment,
Map parameterTypes,
boolean callable) {
super(
query.trim(), /* trim done to workaround stupid oracle bug that cant handle whitespaces before a { in a sp */
cacheable,
cacheRegion,
timeout,
fetchSize,
flushMode,
cacheMode,
readOnly,
comment,
parameterTypes
);
this.resultSetRef = resultSetRef;
this.querySpaces = querySpaces;
this.callable = callable;
}
private void reindexDependents(final HibernateTemplate hibernateTemplate, final Session session, final BaseDO< ? > obj,
final Set<String> alreadyReindexed)
{
if (alreadyReindexed.contains(getReindexId(obj)) == true) {
if (log.isDebugEnabled() == true) {
log.debug("Object already re-indexed (skipping): " + getReindexId(obj));
}
return;
}
session.flush(); // Needed to flush the object changes!
final FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.setFlushMode(FlushMode.AUTO);
fullTextSession.setCacheMode(CacheMode.IGNORE);
try {
BaseDO< ? > dbObj = (BaseDO< ? >) session.get(obj.getClass(), obj.getId());
if (dbObj == null) {
dbObj = (BaseDO< ? >) session.load(obj.getClass(), obj.getId());
}
fullTextSession.index(dbObj);
alreadyReindexed.add(getReindexId(dbObj));
if (log.isDebugEnabled() == true) {
log.debug("Object added to index: " + getReindexId(dbObj));
}
} catch (final Exception ex) {
// Don't fail if any exception while re-indexing occurs.
log.info("Fail to re-index " + obj.getClass() + ": " + ex.getMessage());
}
// session.flush(); // clear every batchSize since the queue is processed
final List<Entry> entryList = map.get(obj.getClass());
reindexDependents(hibernateTemplate, session, obj, entryList, alreadyReindexed);
}
public static CacheMode getCacheMode(Object value) {
if ( value instanceof CacheMode ) {
return (CacheMode) value;
}
else {
return CacheMode.valueOf( (String) value );
}
}
/**
* This form used to construct a NamedSQLQueryDefinition from the binder
* code when a the result-set mapping information is explicitly
* provided in the query definition (i.e., no resultset-mapping used)
*
* @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)
*/
public NamedSQLQueryDefinition(
String query,
NativeSQLQueryReturn[] queryReturns,
List querySpaces,
boolean cacheable,
String cacheRegion,
Integer timeout,
Integer fetchSize,
FlushMode flushMode,
CacheMode cacheMode,
boolean readOnly,
String comment,
Map parameterTypes,
boolean callable) {
super(
query.trim(), /* trim done to workaround stupid oracle bug that cant handle whitespaces before a { in a sp */
cacheable,
cacheRegion,
timeout,
fetchSize,
flushMode,
cacheMode,
readOnly,
comment,
parameterTypes
);
this.queryReturns = queryReturns;
this.querySpaces = querySpaces;
this.callable = callable;
}
/**
* Given a JPA {@link CacheStoreMode} and {@link CacheRetrieveMode}, determine the corresponding
* legacy Hibernate {@link CacheMode}.
*
* @param storeMode The JPA shared-cache store mode.
* @param retrieveMode The JPA shared-cache retrieve mode.
*
* @return Corresponding {@link CacheMode}.
*/
public static CacheMode effectiveCacheMode(CacheStoreMode storeMode, CacheRetrieveMode retrieveMode) {
if ( storeMode == null && retrieveMode == null ) {
return null;
}
if ( storeMode == null ) {
storeMode = DEFAULT_STORE_MODE;
}
if ( retrieveMode == null ) {
retrieveMode = DEFAULT_RETRIEVE_MODE;
}
final boolean get = ( CacheRetrieveMode.USE == retrieveMode );
switch ( storeMode ) {
case USE: {
return get ? CacheMode.NORMAL : CacheMode.PUT;
}
case REFRESH: {
// really (get == true) here is a bit of an invalid combo...
return CacheMode.REFRESH;
}
case BYPASS: {
return get ? CacheMode.GET : CacheMode.IGNORE;
}
default: {
throw new IllegalStateException( "huh? :)" );
}
}
}
public static CacheRetrieveMode interpretCacheRetrieveMode(CacheMode cacheMode) {
if ( cacheMode == null ) {
cacheMode = DEFAULT_LEGACY_MODE;
}
return ( CacheMode.NORMAL == cacheMode || CacheMode.GET == cacheMode )
? CacheRetrieveMode.USE
: CacheRetrieveMode.BYPASS;
}
/**
* 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
);
}
/**
* 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
);
}
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;
}
/**
* 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
);
}
/**
* Returns a single User matches with the given id.
* <p>
* Status Code:
* Not Found 404
*
* @param credentials injected by {@link RobeAuth} annotation for authentication.
* @param id This is the oid of {@link User}
* @return a {@link User} resource matches with the given id.
*/
@RobeService(group = "User", description = "Returns a User resource matches with the given id.")
@Path("{id}")
@GET
@UnitOfWork(readOnly = true, cacheMode = CacheMode.GET, flushMode = FlushMode.MANUAL)
public User get(@RobeAuth Credentials credentials, @PathParam("id") String id) {
User entity = userDao.findById(id);
if (entity == null) {
throw new WebApplicationException(Response.status(404).build());
}
return entity;
}
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;
}
private static boolean useMinimalPuts(SharedSessionContractImplementor session, EntityEntry entityEntry) {
if ( session.getFactory().getSessionFactoryOptions().isMinimalPutsEnabled() ) {
return session.getCacheMode() != CacheMode.REFRESH;
}
else {
return entityEntry.getPersister().hasLazyProperties()
&& entityEntry.getPersister().isLazyPropertiesCacheable();
}
}
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();
}
}
/**
* Returns all {@link User}s as a collection.
*
* @param credentials injected by {@link RobeAuth} annotation for authentication.
* @return all {@link User}s as a collection with.
*/
@RobeService(group = "User", description = "Returns all Users as a collection.")
@GET
@UnitOfWork(readOnly = true, cacheMode = CacheMode.GET, flushMode = FlushMode.MANUAL)
public List<User> getAll(@RobeAuth Credentials credentials, @SearchParam SearchModel search) {
return userDao.findAllStrict(search);
}
public static CacheMode fromXml(String name) {
for ( CacheMode mode : CacheMode.values() ) {
if ( mode.name().equalsIgnoreCase( name ) ) {
return mode;
}
}
return CacheMode.NORMAL;
}
@Override
public ReactiveQueryImpl<R> setCacheMode(CacheMode cacheMode) {
super.setCacheMode(cacheMode);
return this;
}