本文整理匯總了Java中org.springframework.transaction.support.TransactionSynchronizationManager類的典型用法代碼示例。如果您正苦於以下問題:Java TransactionSynchronizationManager類的具體用法?Java TransactionSynchronizationManager怎麽用?Java TransactionSynchronizationManager使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
TransactionSynchronizationManager類屬於org.springframework.transaction.support包,在下文中一共展示了TransactionSynchronizationManager類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: handleComposeMessageCreateCommand
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
private void handleComposeMessageCreateCommand(final Object obj) throws IOException {
final ComposeMessageCreateCommand cmd = (ComposeMessageCreateCommand) obj;
final Message message = new MessageBuilder().transferId(cmd.getTransferId())
.messageState(MessageState.TO_COMPOSE).build();
message.setInternalData(InternalDataUtils.convertInternalDataToJson(cmd.getData()));
final BasicOutboundConfiguration configuration =
basicConfigurationRepository.findOne(cmd.getConfigId());
message.setOutboundConfiguration(configuration);
messageRepository.save((MessageImpl) message);
final String actorId = getContext().parent().path().name();
TransactionSynchronizationManager
.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
LOG.info("Saved new [{}]", message);
getSender().tell(new ComposeMessageCreatedEvent(actorId, message.getId()), getSelf());
stop();
}
});
}
示例2: afterCompletion
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
String participateAttributeName = getParticipateAttributeName();
Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
if (count != null) {
// Do not modify the PersistenceManager: just clear the marker.
if (count > 1) {
request.setAttribute(participateAttributeName, count - 1, WebRequest.SCOPE_REQUEST);
}
else {
request.removeAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST);
}
}
else {
PersistenceManagerHolder pmHolder = (PersistenceManagerHolder)
TransactionSynchronizationManager.unbindResource(getPersistenceManagerFactory());
logger.debug("Closing JDO PersistenceManager in OpenPersistenceManagerInViewInterceptor");
PersistenceManagerFactoryUtils.releasePersistenceManager(
pmHolder.getPersistenceManager(), getPersistenceManagerFactory());
}
}
示例3: getSession
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
/**
* <strong>此方法僅限與bdf2-core模塊配合使用,且隻能用於不加事務的方法當中,如果當前方法或當前方便的調用方法需要用到事務,
* 一定不能使用該方法,否則事務將不起作用</strong><br>
* 此方法返回當前線程當中指定的數據源對應的Session,如線程中未指定,則返回默認的Session,<br>
* 注意此方法返回的Session對象我們在使用完畢之後,無需將其close,<br>
* 在線程執行完畢時,BDF會自動將此方法產生的Session對象進行close處理;同時,此方法僅限在標準的WEB請求調用時使用,<br>
* 如果在後台的JOB中調用此方法可能會有異常拋出
*
* @return 返回一個標準的Hibernate Session對象
*/
public Session getSession() {
String dsName = sessionFactoryRepository.getDefaultSessionFactoryName();
dsName = this.getDataSourceName(dsName);
if (StringUtils.isEmpty(TransactionSynchronizationManager.getCurrentTransactionName())) {
Map<String, Session> map = ContextHolder.getHibernateSessionMap();
if (map == null) {
throw new RuntimeException("This method can only used in bdf2-core module");
}
if (map.containsKey(dsName) && map.get(dsName).isOpen()) {
return map.get(dsName);
} else {
if (map.containsKey(dsName)) {
map.remove(dsName);
}
Session session = getSessionFactory().openSession();
map.put(dsName, session);
return session;
}
} else {
return this.getSessionFactory(dsName).getCurrentSession();
}
}
示例4: startNewThread
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
public boolean startNewThread(ActivityRunner runner) {
boolean wasStarted = false;
if (isStarted()) {
synchronized (runningActivities) {
Assert.isFalse(runningActivities.contains(runner.getActivityId()), "Error");
runningActivities.add(runner.getActivityId());
connectionCapManager.add(runner.getActivityName(), runner.getActivityId());
// TX Synchro
try {
final ThreadStarterSynchronization synchro = new ThreadStarterSynchronization(runner);
TransactionSynchronizationManager.registerSynchronization(synchro);
wasStarted = true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if (runner.isTopActivity()) {
synchronized (runningTopActivities) {
runningTopActivities.add(runner.getActivityId());
}
}
}
return wasStarted;
}
示例5: intercept
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
@Override
public Object intercept(Invocation invocation) throws Throwable {
boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
//如果沒有事務
if (!synchronizationActive) {
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];
DynamicDataSourceGlobal dynamicDataSourceGlobal;
if ((dynamicDataSourceGlobal = CACHE_MAP.get(ms.getId())) == null) {
dynamicDataSourceGlobal = getDynamicDataSource(ms, objects[1]);
LOGGER.warn("設置方法[{}] use [{}] Strategy, SqlCommandType [{}]..", ms.getId(), dynamicDataSourceGlobal.name(), ms.getSqlCommandType().name());
CACHE_MAP.put(ms.getId(), dynamicDataSourceGlobal);
}
DynamicDataSourceHolder.putDataSource(dynamicDataSourceGlobal);
}
return invocation.proceed();
}
示例6: getTransactionId
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
/**
* Get the transaction identifier used to store it in the transaction map.
*
* @param tx Transaction
* @param storeRef StoreRef
* @return - the transaction id
*/
@SuppressWarnings("unchecked")
private String getTransactionId(Transaction tx, StoreRef storeRef)
{
if (tx instanceof SimpleTransaction)
{
SimpleTransaction simpleTx = (SimpleTransaction) tx;
return simpleTx.getGUID();
}
else if (TransactionSynchronizationManager.isSynchronizationActive())
{
Map<StoreRef, LuceneIndexer> indexers = (Map<StoreRef, LuceneIndexer>) AlfrescoTransactionSupport.getResource(indexersKey);
if (indexers != null)
{
LuceneIndexer indexer = indexers.get(storeRef);
if (indexer != null)
{
return indexer.getDeltaId();
}
}
}
return null;
}
示例7: postUpdate
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
@PostUpdate
@Async
public void postUpdate(Object object) {
LOG.info("Listening to post update for object:" + object);
// Entitys have to be annotated with @EventListeners and reference this class in that annotation, because of this
// the usages of this class are not executed withing the handle of the Spring context. So now we have to use this funky
// ass way of wiring in fields AS this method is being called. #sadface
AutowireHelper.autowire(this);
// Trying to just add @Transactional(Transactional.TxType.REQUIRES_NEW) to this method didn't work at all, it was just being ignored.
// This wrapper is what ended up working.
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCompletion(int status) {
super.afterCompletion(status);
List<Webhook> hooks = webhookManager.retrieveWebhooksByEntityNameAndEventType(object.getClass().getSimpleName(), "post-update");
hooks.stream().forEach(wh -> webhookProcessor.notifyWebhook(wh, object));
}
});
}
示例8: getSession
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
/**
* <strong>此方法僅限與bdf2-core模塊配合使用,且隻能用於不加事務的方法當中,如果當前方法或當前方便的調用方法需要用到事務,一定不能使用該方法,否則事務將不起作用</strong><br>
* 此方法返回當前線程當中指定的數據源對應的Session,如線程中未指定,則返回默認的Session,<br>
* 注意此方法返回的Session對象我們在使用完畢之後,無需將其close,<br>
* 在線程執行完畢時,BDF會自動將此方法產生的Session對象進行close處理;同時,此方法僅限在標準的WEB請求調用時使用,<br>
* 如果在後台的JOB中調用此方法可能會有異常拋出
* @return 返回一個標準的Hibernate Session對象
*/
public Session getSession(){
String dsName=sessionFactoryRepository.getDefaultSessionFactoryName();
dsName=this.getDataSourceName(dsName);
if(StringUtils.isEmpty(TransactionSynchronizationManager.getCurrentTransactionName())){
Map<String,Session> map=ContextHolder.getHibernateSessionMap();
if(map==null){
throw new RuntimeException("This method can only used in bdf2-core module");
}
if(map.containsKey(dsName) && map.get(dsName).isOpen()){
return map.get(dsName);
}else{
if(map.containsKey(dsName)){
map.remove(dsName);
}
Session session=getSessionFactory().openSession();
map.put(dsName, session);
return session;
}
}else{
return this.getSessionFactory(dsName).getCurrentSession();
}
}
示例9: afterCompletion
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
/**
* Unbind the Hibernate {@code Session} from the thread and close it (in
* single session mode), or process deferred close for all sessions that have
* been opened during the current request (in deferred close mode).
* @see org.springframework.transaction.support.TransactionSynchronizationManager
*/
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
if (!decrementParticipateCount(request)) {
if (isSingleSession()) {
// single session mode
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
logger.debug("Closing single Hibernate Session in OpenSessionInViewInterceptor");
SessionFactoryUtils.closeSession(sessionHolder.getSession());
}
else {
// deferred close mode
SessionFactoryUtils.processDeferredClose(getSessionFactory());
}
}
}
示例10: createOrRetrieveClassPrimaryKey
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
/**
* Retrieves the primary key from {@code acl_class}, creating a new row if needed and the
* {@code allowCreate} property is {@code true}.
*
* @param type to find or create an entry for (often the fully-qualified class name)
* @param allowCreate true if creation is permitted if not found
*
* @return the primary key or null if not found
*/
protected AclClass createOrRetrieveClassPrimaryKey(String type, boolean allowCreate) {
List<AclClass> classIds = aclDao.findAclClassList(type);
if (!classIds.isEmpty()) {
return classIds.get(0);
}
if (allowCreate) {
AclClass clazz = new AclClass();
clazz.setClazz(type);
Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(),
"Transaction must be running");
return aclDao.createAclClass(clazz);
}
return null;
}
示例11: invoke
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
SessionFactory sf = getSessionFactory();
if (!TransactionSynchronizationManager.hasResource(sf)) {
// New Session to be bound for the current method's scope...
Session session = openSession();
try {
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
return invocation.proceed();
}
finally {
SessionFactoryUtils.closeSession(session);
TransactionSynchronizationManager.unbindResource(sf);
}
}
else {
// Pre-bound Session found -> simply proceed.
return invocation.proceed();
}
}
示例12: execute
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
@Override
public void execute(final AssignUsersMessage.Request request) throws Exception {
request.getUserAssignments().forEach(assignment -> {
final Subject subject = subjectRepository
.getSubjectForSubjectModelInProcess(request.getPiId(), assignment.getSmId());
if (subject != null) {
subject.setUser(assignment.getUserId());
subjectRepository.save((SubjectImpl) subject);
LOG.info("New user for subject: {}", subject);
}
});
final ActorRef sender = getSender();
TransactionSynchronizationManager
.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
sender.tell(new AssignUsersMessage.Response(), getSelf());
}
});
}
示例13: handleStoreExternalDataCommand
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
private void handleStoreExternalDataCommand(final Object obj) {
final StoreExternalDataCommand cmd = (StoreExternalDataCommand) obj;
final Message message = messageRepository.findOne(cmd.getId());
message.setExternalData(cmd.getData());
message.setMessageState(MessageState.COMPOSED);
messageRepository.save((MessageImpl) message);
final String actorId = getContext().parent().path().name();
final ActorRef sender = getSender();
TransactionSynchronizationManager
.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
LOG.info("Updated external data of [{}]", message);
sender.tell(new ComposedMessageEvent(actorId, message.getId()), getSelf());
stop();
}
});
}
示例14: afterCompletion
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
@Override
public void afterCompletion(int status) {
// If we haven't closed the Connection in beforeCompletion,
// close it now. The holder might have been used for other
// cleanup in the meantime, for example by a Hibernate Session.
if (this.holderActive) {
// The thread-bound ConnectionHolder might not be available anymore,
// since afterCompletion might get called from a different thread.
TransactionSynchronizationManager.unbindResourceIfPossible(this.dataSource);
this.holderActive = false;
if (this.connectionHolder.hasConnection()) {
releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
// Reset the ConnectionHolder: It might remain bound to the thread.
this.connectionHolder.setConnection(null);
}
}
this.connectionHolder.reset();
}
示例15: doGetConnection
import org.springframework.transaction.support.TransactionSynchronizationManager; //導入依賴的package包/類
/**
* Actually obtain a CCI Connection from the given ConnectionFactory.
* Same as {@link #getConnection}, but throwing the original ResourceException.
* <p>Is aware of a corresponding Connection bound to the current thread, for example
* when using {@link CciLocalTransactionManager}. Will bind a Connection to the thread
* if transaction synchronization is active (e.g. if in a JTA transaction).
* <p>Directly accessed by {@link TransactionAwareConnectionFactoryProxy}.
* @param cf the ConnectionFactory to obtain Connection from
* @return a CCI Connection from the given ConnectionFactory
* @throws ResourceException if thrown by CCI API methods
* @see #doReleaseConnection
*/
public static Connection doGetConnection(ConnectionFactory cf) throws ResourceException {
Assert.notNull(cf, "No ConnectionFactory specified");
ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(cf);
if (conHolder != null) {
return conHolder.getConnection();
}
logger.debug("Opening CCI Connection");
Connection con = cf.getConnection();
if (TransactionSynchronizationManager.isSynchronizationActive()) {
logger.debug("Registering transaction synchronization for CCI Connection");
conHolder = new ConnectionHolder(con);
conHolder.setSynchronizedWithTransaction(true);
TransactionSynchronizationManager.registerSynchronization(new ConnectionSynchronization(conHolder, cf));
TransactionSynchronizationManager.bindResource(cf, conHolder);
}
return con;
}