本文整理汇总了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;
}