下面列出了怎么用org.hibernate.FlushMode的API类实例代码及写法,或者点击链接到github查看源代码。
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
super.afterTest();
Session s = store.session(null);
if (s == null)
return;
try {
s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
.setFlushMode(FlushMode.ALWAYS).executeUpdate();
Transaction hTx = s.getTransaction();
if (hTx != null && hTx.isActive())
hTx.commit();
}
finally {
s.close();
}
}
public static FlushMode fromXml(String name) {
// valid values are a subset of all FlushMode possibilities, so we will
// handle the conversion here directly.
// Also, we want to map "never"->MANUAL (rather than NEVER)
if ( name == null ) {
return null;
}
if ( "never".equalsIgnoreCase( name ) ) {
return FlushMode.MANUAL;
}
else if ( "auto".equalsIgnoreCase( name ) ) {
return FlushMode.AUTO;
}
else if ( "always".equalsIgnoreCase( name ) ) {
return FlushMode.ALWAYS;
}
// if the incoming value was not null *and* was not one of the pre-defined
// values, we need to throw an exception. This *should never happen if the
// document we are processing conforms to the schema...
throw new HibernateException( "Unrecognized flush mode : " + name );
}
SessionBuilderImpl(SessionFactoryImpl sessionFactory) {
this.sessionFactory = sessionFactory;
this.sessionOwner = null;
// set up default builder values...
this.statementInspector = sessionFactory.getSessionFactoryOptions().getStatementInspector();
this.connectionHandlingMode = sessionFactory.getSessionFactoryOptions().getPhysicalConnectionHandlingMode();
this.autoClose = sessionFactory.getSessionFactoryOptions().isAutoCloseSessionEnabled();
this.flushMode = sessionFactory.getSessionFactoryOptions().isFlushBeforeCompletionEnabled()
? FlushMode.AUTO
: FlushMode.MANUAL;
if ( sessionFactory.getCurrentTenantIdentifierResolver() != null ) {
tenantIdentifier = sessionFactory.getCurrentTenantIdentifierResolver().resolveCurrentTenantIdentifier();
}
this.jdbcTimeZone = sessionFactory.getSessionFactoryOptions().getJdbcTimeZone();
listeners = sessionFactory.getSessionFactoryOptions().getBaselineSessionEventsListenerBuilder().buildBaselineList();
queryParametersValidationEnabled = sessionFactory.getSessionFactoryOptions().isQueryParametersValidationEnabled();
}
@Override
public Mutiny.Session setFlushMode(FlushMode flushMode) {
switch (flushMode) {
case COMMIT:
delegate.setHibernateFlushMode(FlushMode.COMMIT);
break;
case AUTO:
delegate.setHibernateFlushMode(FlushMode.AUTO);
break;
case MANUAL:
delegate.setHibernateFlushMode(FlushMode.MANUAL);
break;
case ALWAYS:
delegate.setHibernateFlushMode(FlushMode.ALWAYS);
break;
}
return this;
}
@Override
public void onPostInsert(PostInsertEvent event) throws HibernateException {
final Object entity = event.getEntity();
if(entity instanceof Post) {
Post post = (Post) entity;
event.getSession().createNativeQuery(
"INSERT INTO old_post (id, title, version) " +
"VALUES (:id, :title, :version)")
.setParameter("id", post.getId())
.setParameter("title", post.getTitle())
.setParameter("version", post.getVersion())
.setFlushMode(FlushMode.MANUAL)
.executeUpdate();
}
}
@Test
public void testInterceptorWithThreadBoundAndFlushEagerSwitch() throws HibernateException {
given(session.isOpen()).willReturn(true);
given(session.getFlushMode()).willReturn(FlushMode.NEVER);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
HibernateInterceptor interceptor = new HibernateInterceptor();
interceptor.setFlushMode(HibernateInterceptor.FLUSH_EAGER);
interceptor.setSessionFactory(sessionFactory);
try {
interceptor.invoke(invocation);
}
catch (Throwable t) {
fail("Should not have thrown Throwable: " + t.getMessage());
}
finally {
TransactionSynchronizationManager.unbindResource(sessionFactory);
}
InOrder ordered = inOrder(session);
ordered.verify(session).setFlushMode(FlushMode.AUTO);
ordered.verify(session).flush();
ordered.verify(session).setFlushMode(FlushMode.NEVER);
}
@Override
public Uni<SecurityIdentity> authenticate(UsernamePasswordAuthenticationRequest request,
AuthenticationRequestContext context) {
return context.runBlocking(new Supplier<SecurityIdentity>() {
@Override
public SecurityIdentity get() {
// FIXME: unit name
EntityManager em = jpaConfig.getEntityManagerFactory(null).createEntityManager();
((org.hibernate.Session) em).setHibernateFlushMode(FlushMode.MANUAL);
((org.hibernate.Session) em).setDefaultReadOnly(true);
try {
return authenticate(em, request);
} catch (SecurityException e) {
log.debug("Authentication failed", e);
throw new AuthenticationFailedException();
} finally {
em.close();
}
}
});
}
@Override
public Uni<SecurityIdentity> authenticate(TrustedAuthenticationRequest request,
AuthenticationRequestContext context) {
return context.runBlocking(new Supplier<SecurityIdentity>() {
@Override
public SecurityIdentity get() {
// FIXME: unit name
EntityManager em = jpaConfig.getEntityManagerFactory(null).createEntityManager();
((org.hibernate.Session) em).setHibernateFlushMode(FlushMode.MANUAL);
((org.hibernate.Session) em).setDefaultReadOnly(true);
try {
return authenticate(em, request);
} catch (SecurityException e) {
log.debug("Authentication failed", e);
throw new AuthenticationFailedException();
} finally {
em.close();
}
}
});
}
@Override
protected void prepareForCommit(DefaultTransactionStatus status) {
if (this.earlyFlushBeforeCommit && status.isNewTransaction()) {
HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction();
Session session = txObject.getSessionHolder().getSession();
if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) {
logger.debug("Performing an early flush for Hibernate transaction");
try {
session.flush();
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
finally {
session.setFlushMode(FlushMode.MANUAL);
}
}
}
}
private static FlushMode getFlushMode(FlushModeType flushModeType) {
FlushMode flushMode;
switch ( flushModeType ) {
case ALWAYS:
flushMode = FlushMode.ALWAYS;
break;
case AUTO:
flushMode = FlushMode.AUTO;
break;
case COMMIT:
flushMode = FlushMode.COMMIT;
break;
case NEVER:
flushMode = FlushMode.MANUAL;
break;
case MANUAL:
flushMode = FlushMode.MANUAL;
break;
case PERSISTENCE_CONTEXT:
flushMode = null;
break;
default:
throw new AssertionFailure( "Unknown flushModeType: " + flushModeType );
}
return flushMode;
}
@Override
public Object prepareTransaction(EntityManager entityManager, boolean readOnly, @Nullable String name)
throws PersistenceException {
Session session = getSession(entityManager);
FlushMode previousFlushMode = prepareFlushMode(session, readOnly);
return new SessionTransactionData(session, previousFlushMode, null, null);
}
@Test
public void testUpdateWithLockMode() throws HibernateException {
TestBean tb = new TestBean();
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
hibernateTemplate.update(tb, LockMode.UPGRADE);
verify(session).update(tb);
verify(session).lock(tb, LockMode.UPGRADE);
verify(session).flush();
verify(session).close();
}
@Override
public void deleteMark(OLATResourceable ores) {
StringBuilder sb = new StringBuilder();
sb.append("delete from ").append(MarkImpl.class.getName()).append(" mark where ").append("mark.resId=:resId and mark.resName=:resName");
DBQuery query = database.createQuery(sb.toString());
query.setString("resName", ores.getResourceableTypeName());
query.setLong("resId", ores.getResourceableId());
query.executeUpdate(FlushMode.AUTO);
}
/**
* Open a Session for the given SessionFactory.
* <p>The default implementation delegates to the {@link SessionFactory#openSession}
* method and sets the {@link Session}'s flush mode to "MANUAL".
* @param sessionFactory the SessionFactory to use
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @since 5.0
* @see FlushMode#MANUAL
*/
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = openSession();
if (session == null) {
try {
session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
return session;
}
@Test
public void testMergeWithEntityName() throws HibernateException {
TestBean tb = new TestBean();
TestBean tbMerged = new TestBean();
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
given(session.merge("myEntity", tb)).willReturn(tbMerged);
assertSame(tbMerged, hibernateTemplate.merge("myEntity", tb));
verify(session).flush();
verify(session).close();
}
@Override
@SuppressWarnings("deprecation")
protected Session buildOrObtainSession() {
Session session = super.buildOrObtainSession();
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.MANUAL);
}
return session;
}
@Test
public void testSaveOrUpdateWithFlushModeNever() throws HibernateException {
TestBean tb = new TestBean();
given(session.getFlushMode()).willReturn(FlushMode.MANUAL);
try {
hibernateTemplate.saveOrUpdate(tb);
fail("Should have thrown InvalidDataAccessApiUsageException");
}
catch (InvalidDataAccessApiUsageException ex) {
// expected
}
verify(session).close();
}
public static String toXml(FlushMode mode) {
if ( mode == null ) {
return null;
}
// conversely, we want to map MANUAL -> "never" here
if ( mode == FlushMode.MANUAL ) {
return "never";
}
// todo : what to do if the incoming value does not conform to allowed values?
// for now, we simply don't deal with that (we write it out).
return mode.name().toLowerCase( Locale.ENGLISH );
}
/**
* Private constructor
*
* @param transactionWrapper {@link TransactionWrapper}
* @param exceptionHandler {@link TransactionExceptionHandler}
* @param flushMode {@link FlushMode}
*/
private Transaction(TransactionWrapper transactionWrapper, TransactionExceptionHandler exceptionHandler, FlushMode flushMode) {
this.transactionWrapper = transactionWrapper;
this.exceptionHandler = exceptionHandler;
this.flushMode = flushMode;
storePreviousSession();
configureNewSession();
start();
}
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;
}
@Test
public void testDeleteWithEntityName() {
TestBean tb = new TestBean();
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
hibernateTemplate.delete("myEntity", tb);
verify(session).delete("myEntity", tb);
}
@Transactional
public T insert(T object) {
sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
sessionFactory.getCurrentSession().save(object);
sessionFactory.getCurrentSession().flush();
return object;
}
@Test
public void testUpdate() throws HibernateException {
TestBean tb = new TestBean();
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
hibernateTemplate.update(tb);
verify(session).update(tb);
verify(session).flush();
verify(session).close();
}
/**
* Open a Session for the SessionFactory that this filter uses.
* <p>The default implementation delegates to the {@link SessionFactory#openSession}
* method and sets the {@link Session}'s flush mode to "MANUAL".
* @param sessionFactory the SessionFactory that this filter uses
* @return the Session to use
* @throws DataAccessResourceFailureException if the Session could not be created
* @see FlushMode#MANUAL
*/
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
try {
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
/**
* Demonstrates HQL with runtime fetch strategy
*/
public void viewAllAuctionsSlow() throws Exception {
System.out.println("Viewing all auction item objects");
Session s = factory.openSession();
Transaction tx=null;
try {
s.setFlushMode(FlushMode.NEVER); //entirely optional!!
tx = s.beginTransaction();
List auctions = s.createQuery(
"from AuctionItem item "
+ "left join fetch item.bids bid left join fetch bid.bidder "
+ "order by item.ends desc"
)
.setMaxResults(100)
.list();
Iterator iter = new HashSet(auctions).iterator();
while ( iter.hasNext() ) {
AuctionItem auction = (AuctionItem) iter.next();
System.out.println(
"Auction: " + auction.getId() + " - " + auction.getDescription() +
", ends: " + auction.getEnds() +
", bids: " + auction.getBids()
);
}
System.out.println();
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
s.close();
}
}
@Test
public void testMerge() {
TestBean tb = new TestBean();
TestBean tbMerged = new TestBean();
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
given(session.merge(tb)).willReturn(tbMerged);
assertSame(tbMerged, hibernateTemplate.merge(tb));
}
@Test
@SuppressWarnings("rawtypes")
public void testJtaSessionSynchronization() throws Exception {
TransactionManager tm = mock(TransactionManager.class);
MockJtaTransaction transaction = new MockJtaTransaction();
given(tm.getTransaction()).willReturn(transaction);
final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
final Session session = mock(Session.class);
given(sf.openSession()).willReturn(session);
given(sf.getTransactionManager()).willReturn(tm);
given(session.isOpen()).willReturn(true);
given(session.getFlushMode()).willReturn(FlushMode.AUTO);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
HibernateTemplate ht = new HibernateTemplate(sf);
ht.setExposeNativeSession(true);
for (int i = 0; i < 5; i++) {
ht.executeFind(new HibernateCallback() {
@Override
public Object doInHibernate(org.hibernate.Session sess) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
assertEquals(session, sess);
return null;
}
});
}
Synchronization synchronization = transaction.getSynchronization();
assertTrue("JTA synchronization registered", synchronization != null);
synchronization.beforeCompletion();
synchronization.afterCompletion(Status.STATUS_COMMITTED);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
verify(session).flush();
verify(session).close();
}
@Transactional
public T insertOrUpdate(T object) {
sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
sessionFactory.getCurrentSession().saveOrUpdate(object);
sessionFactory.getCurrentSession().flush();
return object;
}
public void updateDuration(LoggingObject lastLogObj, long duration) {
if (db != null && db.isError()) {
// then we would run into an ERROR when we'd do more with this DB
// hence we just issue a log.info here with the details
// @TODO: lower to log.info once we checked that it doesn't occur very often (best for 6.4)
log.warn("log: DB is in Error state therefore the UserActivityLoggerImpl cannot update the simpleDuration of log_id " + lastLogObj.getKey() + " with value "
+ duration + ", loggingObject: " + lastLogObj);
} else {
DBQuery update = db.createQuery("update LoggingObject set simpleDuration = :duration where log_id = :logid");
update.setLong("duration", duration);
update.setLong("logid", lastLogObj.getKey());
// we have to do FlushMode.AUTO (which is the default anyway)
update.executeUpdate(FlushMode.AUTO);
}
}
SQLQueryImpl(
final String sql,
final List queryReturns,
final Collection querySpaces,
final FlushMode flushMode,
boolean callable,
final SessionImplementor session,
ParameterMetadata parameterMetadata) {
// TODO : absolutely no usages of this constructor form; can it go away?
super( sql, flushMode, session, parameterMetadata );
this.queryReturns = queryReturns;
this.querySpaces = querySpaces;
this.callable = callable;
}