Here are the examples of the java api org.springframework.transaction.PlatformTransactionManager.getTransaction() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
61 Examples
19
View Source File : AbstractTransactionAspectTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Check that the given exception thrown by the target can produce the
* desired behavior with the appropriate transaction attribute.
* @param ex exception to be thrown by the target
* @param shouldRollback whether this should cause a transaction rollback
*/
@SuppressWarnings("serial")
protected void doTestRollbackOnException(final Exception ex, final boolean shouldRollback, boolean rollbackException) throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute() {
@Override
public boolean rollbackOn(Throwable t) {
replacedertTrue(t == ex);
return shouldRollback;
}
};
Method m = exceptionalMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
TransactionStatus status = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// Gets additional call(s) from TransactionControl
given(ptm.getTransaction(txatt)).willReturn(status);
TransactionSystemException tex = new TransactionSystemException("system exception");
if (rollbackException) {
if (shouldRollback) {
willThrow(tex).given(ptm).rollback(status);
} else {
willThrow(tex).given(ptm).commit(status);
}
}
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
try {
itb.exceptional(ex);
fail("Should have thrown exception");
} catch (Throwable t) {
if (rollbackException) {
replacedertEquals("Caught wrong exception", tex, t);
} else {
replacedertEquals("Caught wrong exception", ex, t);
}
}
if (!rollbackException) {
if (shouldRollback) {
verify(ptm).rollback(status);
} else {
verify(ptm).commit(status);
}
}
}
19
View Source File : AbstractTransactionAspectTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void enclosingTransactionWithNestedTransactionOnAdvisedInside() throws Throwable {
final TransactionAttribute outerTxatt = new DefaultTransactionAttribute();
final TransactionAttribute innerTxatt = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_NESTED);
Method outerMethod = exceptionalMethod;
Method innerMethod = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(outerMethod, outerTxatt);
tas.register(innerMethod, innerTxatt);
TransactionStatus outerStatus = mock(TransactionStatus.clreplaced);
TransactionStatus innerStatus = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// Expect a transaction
given(ptm.getTransaction(outerTxatt)).willReturn(outerStatus);
given(ptm.getTransaction(innerTxatt)).willReturn(innerStatus);
final String spouseName = "innerName";
TestBean outer = new TestBean() {
@Override
public void exceptional(Throwable t) throws Throwable {
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
replacedertThat(ti.hasTransaction()).isTrue();
replacedertThat(ti.getTransactionAttribute()).isEqualTo(outerTxatt);
replacedertThat(getSpouse().getName()).isEqualTo(spouseName);
}
};
TestBean inner = new TestBean() {
@Override
public String getName() {
// replacedert that we're in the inner proxy
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
// Has nested transaction
replacedertThat(ti.hasTransaction()).isTrue();
replacedertThat(ti.getTransactionAttribute()).isEqualTo(innerTxatt);
return spouseName;
}
};
ITestBean outerProxy = (ITestBean) advised(outer, ptm, tas);
ITestBean innerProxy = (ITestBean) advised(inner, ptm, tas);
outer.setSpouse(innerProxy);
checkTransactionStatus(false);
// Will invoke inner.getName, which is non-transactional
outerProxy.exceptional(null);
checkTransactionStatus(false);
verify(ptm).commit(innerStatus);
verify(ptm).commit(outerStatus);
}
19
View Source File : AbstractTransactionAspectTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Check that the given exception thrown by the target can produce the
* desired behavior with the appropriate transaction attribute.
* @param ex exception to be thrown by the target
* @param shouldRollback whether this should cause a transaction rollback
*/
@SuppressWarnings("serial")
protected void doTestRollbackOnException(final Exception ex, final boolean shouldRollback, boolean rollbackException) throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute() {
@Override
public boolean rollbackOn(Throwable t) {
replacedertThat(t == ex).isTrue();
return shouldRollback;
}
};
Method m = exceptionalMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
TransactionStatus status = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// Gets additional call(s) from TransactionControl
given(ptm.getTransaction(txatt)).willReturn(status);
TransactionSystemException tex = new TransactionSystemException("system exception");
if (rollbackException) {
if (shouldRollback) {
willThrow(tex).given(ptm).rollback(status);
} else {
willThrow(tex).given(ptm).commit(status);
}
}
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
try {
itb.exceptional(ex);
fail("Should have thrown exception");
} catch (Throwable t) {
if (rollbackException) {
replacedertThat(t).as("Caught wrong exception").isEqualTo(tex);
} else {
replacedertThat(t).as("Caught wrong exception").isEqualTo(ex);
}
}
if (!rollbackException) {
if (shouldRollback) {
verify(ptm).rollback(status);
} else {
verify(ptm).commit(status);
}
}
}
19
View Source File : AbstractTransactionAspectTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void enclosingTransactionWithNonTransactionMethodOnAdvisedInside() throws Throwable {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(exceptionalMethod, txatt);
TransactionStatus status = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// Expect a transaction
given(ptm.getTransaction(txatt)).willReturn(status);
final String spouseName = "innerName";
TestBean outer = new TestBean() {
@Override
public void exceptional(Throwable t) throws Throwable {
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
replacedertThat(ti.hasTransaction()).isTrue();
replacedertThat(getSpouse().getName()).isEqualTo(spouseName);
}
};
TestBean inner = new TestBean() {
@Override
public String getName() {
// replacedert that we're in the inner proxy
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
replacedertThat(ti.hasTransaction()).isFalse();
return spouseName;
}
};
ITestBean outerProxy = (ITestBean) advised(outer, ptm, tas);
ITestBean innerProxy = (ITestBean) advised(inner, ptm, tas);
outer.setSpouse(innerProxy);
checkTransactionStatus(false);
// Will invoke inner.getName, which is non-transactional
outerProxy.exceptional(null);
checkTransactionStatus(false);
verify(ptm).commit(status);
}
19
View Source File : TransactionService.java
License : GNU Affero General Public License v3.0
Project Creator : progilone
License : GNU Affero General Public License v3.0
Project Creator : progilone
public TransactionStatus startTransaction(final boolean readonly) {
final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
def.setReadOnly(readonly);
return txManager.getTransaction(def);
}
19
View Source File : SpringTransactionContext.java
License : Apache License 2.0
Project Creator : dingziyang
License : Apache License 2.0
Project Creator : dingziyang
public void rollback() {
// Just in case the rollback isn't triggered by an
// exception, we mark the current transaction rollBackOnly.
transactionManager.getTransaction(null).setRollbackOnly();
}
18
View Source File : SpringTransactionManager.java
License : Apache License 2.0
Project Creator : WeBankFinTech
License : Apache License 2.0
Project Creator : WeBankFinTech
@Override
public Object begin() {
if (platformTransactionManager != null) {
return platformTransactionManager.getTransaction(new DefaultTransactionAttribute());
}
return null;
}
18
View Source File : AbstractTransactionAspectTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Test that TransactionStatus.setRollbackOnly works.
*/
@Test
public void programmaticRollback() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
TransactionStatus status = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
given(ptm.getTransaction(txatt)).willReturn(status);
final String name = "jenny";
TestBean tb = new TestBean() {
@Override
public String getName() {
TransactionStatus txStatus = TransactionInterceptor.currentTransactionStatus();
txStatus.setRollbackOnly();
return name;
}
};
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
// verification!?
replacedertTrue(name.equals(itb.getName()));
verify(ptm).commit(status);
}
18
View Source File : AbstractTransactionAspectTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void enclosingTransactionWithNonTransactionMethodOnAdvisedInside() throws Throwable {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(exceptionalMethod, txatt);
TransactionStatus status = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// Expect a transaction
given(ptm.getTransaction(txatt)).willReturn(status);
final String spouseName = "innerName";
TestBean outer = new TestBean() {
@Override
public void exceptional(Throwable t) throws Throwable {
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
replacedertTrue(ti.hasTransaction());
replacedertEquals(spouseName, getSpouse().getName());
}
};
TestBean inner = new TestBean() {
@Override
public String getName() {
// replacedert that we're in the inner proxy
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
replacedertFalse(ti.hasTransaction());
return spouseName;
}
};
ITestBean outerProxy = (ITestBean) advised(outer, ptm, tas);
ITestBean innerProxy = (ITestBean) advised(inner, ptm, tas);
outer.setSpouse(innerProxy);
checkTransactionStatus(false);
// Will invoke inner.getName, which is non-transactional
outerProxy.exceptional(null);
checkTransactionStatus(false);
verify(ptm).commit(status);
}
18
View Source File : AbstractTransactionAspectTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Simulate a transaction infrastructure failure.
* Shouldn't invoke target method.
*/
@Test
public void cannotCreateTransaction() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// Expect a transaction
CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
given(ptm.getTransaction(txatt)).willThrow(ex);
TestBean tb = new TestBean() {
@Override
public String getName() {
throw new UnsupportedOperationException("Shouldn't have invoked target method when couldn't create transaction for transactional method");
}
};
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
try {
itb.getName();
fail("Shouldn't have invoked method");
} catch (CannotCreateTransactionException thrown) {
replacedertTrue(thrown == ex);
}
}
18
View Source File : AbstractTransactionAspectTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Check that a transaction is created and committed.
*/
@Test
public void transactionShouldSucceedWithNotNew() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(getNameMethod, txatt);
TransactionStatus status = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// expect a transaction
given(ptm.getTransaction(txatt)).willReturn(status);
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
// verification!?
itb.getName();
checkTransactionStatus(false);
verify(ptm).commit(status);
}
18
View Source File : AbstractTransactionAspectTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Check that a transaction is created and committed.
*/
@Test
public void transactionShouldSucceed() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(getNameMethod, txatt);
TransactionStatus status = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// expect a transaction
given(ptm.getTransaction(txatt)).willReturn(status);
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
verify(ptm).commit(status);
}
18
View Source File : AbstractTransactionAspectTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void enclosingTransactionWithNestedTransactionOnAdvisedInside() throws Throwable {
final TransactionAttribute outerTxatt = new DefaultTransactionAttribute();
final TransactionAttribute innerTxatt = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_NESTED);
Method outerMethod = exceptionalMethod;
Method innerMethod = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(outerMethod, outerTxatt);
tas.register(innerMethod, innerTxatt);
TransactionStatus outerStatus = mock(TransactionStatus.clreplaced);
TransactionStatus innerStatus = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// Expect a transaction
given(ptm.getTransaction(outerTxatt)).willReturn(outerStatus);
given(ptm.getTransaction(innerTxatt)).willReturn(innerStatus);
final String spouseName = "innerName";
TestBean outer = new TestBean() {
@Override
public void exceptional(Throwable t) throws Throwable {
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
replacedertTrue(ti.hasTransaction());
replacedertEquals(outerTxatt, ti.getTransactionAttribute());
replacedertEquals(spouseName, getSpouse().getName());
}
};
TestBean inner = new TestBean() {
@Override
public String getName() {
// replacedert that we're in the inner proxy
TransactionInfo ti = TransactionAspectSupport.currentTransactionInfo();
// Has nested transaction
replacedertTrue(ti.hasTransaction());
replacedertEquals(innerTxatt, ti.getTransactionAttribute());
return spouseName;
}
};
ITestBean outerProxy = (ITestBean) advised(outer, ptm, tas);
ITestBean innerProxy = (ITestBean) advised(inner, ptm, tas);
outer.setSpouse(innerProxy);
checkTransactionStatus(false);
// Will invoke inner.getName, which is non-transactional
outerProxy.exceptional(null);
checkTransactionStatus(false);
verify(ptm).commit(innerStatus);
verify(ptm).commit(outerStatus);
}
18
View Source File : AbstractTransactionAspectTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Check that two transactions are created and committed.
*/
@Test
public void twoTransactionsShouldSucceed() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
MapTransactionAttributeSource tas1 = new MapTransactionAttributeSource();
tas1.register(getNameMethod, txatt);
MapTransactionAttributeSource tas2 = new MapTransactionAttributeSource();
tas2.register(setNameMethod, txatt);
TransactionStatus status = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// expect a transaction
given(ptm.getTransaction(txatt)).willReturn(status);
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, new TransactionAttributeSource[] { tas1, tas2 });
checkTransactionStatus(false);
itb.getName();
checkTransactionStatus(false);
itb.setName("myName");
checkTransactionStatus(false);
verify(ptm, times(2)).commit(status);
}
18
View Source File : DefaultTransactionService.java
License : Apache License 2.0
Project Creator : spot-next
License : Apache License 2.0
Project Creator : spot-next
@Override
public TransactionStatus start() throws TransactionException {
Logger.debug(String.format("Creating new transaction for thread %s (id = %s)", Thread.currentThread().getName(), Thread.currentThread().getId()));
if (!getCurrentTransaction().isPresent()) {
final TransactionDefinition def = createTransactionTemplate();
final TransactionStatus status = transactionManager.getTransaction(def);
currentTransaction.set(status);
return status;
} else {
throw new CannotCreateTransactionException("There is already an active transaction.");
// Logger.debug("There is already a transaction running");
}
}
18
View Source File : AbstractTransactionAspectTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Test that TransactionStatus.setRollbackOnly works.
*/
@Test
public void programmaticRollback() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
TransactionStatus status = mock(TransactionStatus.clreplaced);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
given(ptm.getTransaction(txatt)).willReturn(status);
final String name = "jenny";
TestBean tb = new TestBean() {
@Override
public String getName() {
TransactionStatus txStatus = TransactionInterceptor.currentTransactionStatus();
txStatus.setRollbackOnly();
return name;
}
};
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
// verification!?
replacedertThat(name.equals(itb.getName())).isTrue();
verify(ptm).commit(status);
}
18
View Source File : AbstractTransactionAspectTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Simulate a transaction infrastructure failure.
* Shouldn't invoke target method.
*/
@Test
public void cannotCreateTransaction() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = getNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
// Expect a transaction
CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
given(ptm.getTransaction(txatt)).willThrow(ex);
TestBean tb = new TestBean() {
@Override
public String getName() {
throw new UnsupportedOperationException("Shouldn't have invoked target method when couldn't create transaction for transactional method");
}
};
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
try {
itb.getName();
fail("Shouldn't have invoked method");
} catch (CannotCreateTransactionException thrown) {
replacedertThat(thrown == ex).isTrue();
}
}
18
View Source File : AbstractTransactionAspectTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Simulate failure of the underlying transaction infrastructure to commit.
* Check that the target method was invoked, but that the transaction
* infrastructure exception was thrown to the client
*/
@Test
public void cannotCommitTransaction() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = setNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
// Method m2 = getNameMethod;
// No attributes for m2
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
TransactionStatus status = mock(TransactionStatus.clreplaced);
given(ptm.getTransaction(txatt)).willReturn(status);
UnexpectedRollbackException ex = new UnexpectedRollbackException("foobar", null);
willThrow(ex).given(ptm).commit(status);
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
String name = "new name";
try {
itb.setName(name);
fail("Shouldn't have succeeded");
} catch (UnexpectedRollbackException thrown) {
replacedertThat(thrown == ex).isTrue();
}
// Should have invoked target and changed name
replacedertThat(itb.getName() == name).isTrue();
}
18
View Source File : AbstractAsgardConsumer.java
License : Apache License 2.0
Project Creator : open-hand
License : Apache License 2.0
Project Creator : open-hand
protected TransactionStatus createTransactionStatus(final PlatformTransactionManager transactionManager, final int isolationLevel) {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
def.setIsolationLevel(isolationLevel);
return transactionManager.getTransaction(def);
}
18
View Source File : WxOrderController.java
License : MIT License
Project Creator : geekyouth
License : MIT License
Project Creator : geekyouth
/**
* 提交订单
* 1. 根据购物车ID、地址ID、优惠券ID,创建订单表项
* 2. 购物车清空
* 3. TODO 优惠券设置已用
* 4. 商品货品数量减少
*
* @param userId 用户ID
* @param body 订单信息,{ cartId:xxx, addressId: xxx, couponId: xxx }
* @return 订单操作结果
* 成功则 { errno: 0, errmsg: '成功', data: { orderId: xxx } }
* 失败则 { errno: XXX, errmsg: XXX }
*/
@PostMapping("submit")
public Object submit(@LoginUser Integer userId, @RequestBody String body) {
if (userId == null) {
return ResponseUtil.unlogin();
}
if (body == null) {
return ResponseUtil.badArgument();
}
Integer cartId = JacksonUtil.parseInteger(body, "cartId");
Integer addressId = JacksonUtil.parseInteger(body, "addressId");
Integer couponId = JacksonUtil.parseInteger(body, "couponId");
if (cartId == null || addressId == null || couponId == null) {
return ResponseUtil.badArgument();
}
// 收货地址
LitemallAddress checkedAddress = addressService.findById(addressId);
// 获取可用的优惠券信息
// 使用优惠券减免的金额
BigDecimal couponPrice = new BigDecimal(0.00);
// 货品价格
List<LitemallCart> checkedGoodsList = null;
if (cartId.equals(0)) {
checkedGoodsList = cartService.queryByUidAndChecked(userId);
} else {
LitemallCart cart = cartService.findById(cartId);
checkedGoodsList = new ArrayList<>(1);
checkedGoodsList.add(cart);
}
if (checkedGoodsList.size() == 0) {
return ResponseUtil.badArgumentValue();
}
BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
for (LitemallCart checkGoods : checkedGoodsList) {
checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber())));
}
// 根据订单商品总价计算运费,满88则免运费,否则8元;
BigDecimal freightPrice = new BigDecimal(0.00);
if (checkedGoodsPrice.compareTo(SystemConfig.getFreightLimit()) < 0) {
freightPrice = SystemConfig.getFreight();
}
// 可以使用的其他钱,例如用户积分
BigDecimal integralPrice = new BigDecimal(0.00);
// 订单费用
BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice);
BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);
// 开启事务管理
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
Integer orderId = null;
LitemallOrder order = null;
try {
// 订单
order = new LitemallOrder();
order.setUserId(userId);
order.setOrderSn(orderService.generateOrderSn(userId));
order.setAddTime(LocalDateTime.now());
order.setOrderStatus(OrderUtil.STATUS_CREATE);
order.setConsignee(checkedAddress.getName());
order.setMobile(checkedAddress.getMobile());
String detailedAddress = detailedAddress(checkedAddress);
order.setAddress(detailedAddress);
order.setGoodsPrice(checkedGoodsPrice);
order.setFreightPrice(freightPrice);
order.setCouponPrice(couponPrice);
order.setIntegralPrice(integralPrice);
order.setOrderPrice(orderTotalPrice);
order.setActualPrice(actualPrice);
// 添加订单表项
orderService.add(order);
orderId = order.getId();
for (LitemallCart cartGoods : checkedGoodsList) {
// 订单商品
LitemallOrderGoods orderGoods = new LitemallOrderGoods();
orderGoods.setOrderId(order.getId());
orderGoods.setGoodsId(cartGoods.getGoodsId());
orderGoods.setGoodsSn(cartGoods.getGoodsSn());
orderGoods.setProductId(cartGoods.getProductId());
orderGoods.setGoodsName(cartGoods.getGoodsName());
orderGoods.setPicUrl(cartGoods.getPicUrl());
orderGoods.setPrice(cartGoods.getPrice());
orderGoods.setNumber(cartGoods.getNumber());
orderGoods.setSpecifications(cartGoods.getSpecifications());
orderGoods.setAddTime(LocalDateTime.now());
// 添加订单商品表项
orderGoodsService.add(orderGoods);
}
// 删除购物车里面的商品信息
cartService.clearGoods(userId);
// 商品货品数量减少
for (LitemallCart checkGoods : checkedGoodsList) {
Integer productId = checkGoods.getProductId();
LitemallProduct product = productService.findById(productId);
Integer remainNumber = product.getNumber() - checkGoods.getNumber();
if (remainNumber < 0) {
throw new RuntimeException("下单的商品货品数量大于库存量");
}
product.setNumber(remainNumber);
productService.updateById(product);
}
} catch (Exception ex) {
txManager.rollback(status);
logger.error("系统内部错误", ex);
return ResponseUtil.fail(403, "下单失败");
}
txManager.commit(status);
Map<String, Object> data = new HashMap<>();
data.put("orderId", orderId);
return ResponseUtil.ok(data);
}
18
View Source File : SpringTransactionContext.java
License : Apache License 2.0
Project Creator : flowable
License : Apache License 2.0
Project Creator : flowable
@Override
public void rollback() {
// Just in case the rollback isn't triggered by an
// exception, we mark the current transaction rollBackOnly.
transactionManager.getTransaction(null).setRollbackOnly();
}
18
View Source File : WinnerServiceIsolationTest.java
License : Apache License 2.0
Project Creator : csj4032
License : Apache License 2.0
Project Creator : csj4032
@Test
@Order(2)
@DisplayName("READ_COMMITTED_SELECT")
public void read_committed() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setName("READ_COMMITTED_SELECT");
definition.setPropagationBehavior(3);
definition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
TransactionStatus status = transactionManager.getTransaction(definition);
SqlSession localSqlSession = sqlSessionFactory.openSession();
WinnerMapper winnerMapper = localSqlSession.getMapper(WinnerMapper.clreplaced);
List<Winner> winnerList = winnerMapper.findAll();
transactionManager.commit(status);
replacedertions.replacedertTrue(winnerList.isEmpty());
}
18
View Source File : GeronimoPlatformTransactionManager.java
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
return platformTransactionManager.getTransaction(definition);
}
17
View Source File : SpringTransactionManager.java
License : Apache License 2.0
Project Creator : zhongxunking
License : Apache License 2.0
Project Creator : zhongxunking
@Override
public Object getTransaction(TransactionType type) {
TransactionDefinition definition;
switch(type) {
case REQUIRED:
definition = REQUIRED_DEFINITION;
break;
case REQUIRES_NEW:
definition = REQUIRES_NEW_DEFINITION;
break;
case NOT_SUPPORTED:
definition = NOT_SUPPORTED_DEFINITION;
break;
default:
throw new IllegalArgumentException("type不能为null");
}
return transactionManager.getTransaction(definition);
}
17
View Source File : PlatformTransactionManagerFacade.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
public TransactionStatus getTransaction(@Nullable TransactionDefinition definition) {
return delegate.getTransaction(definition);
}
17
View Source File : AbstractTransactionAspectTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Simulate failure of the underlying transaction infrastructure to commit.
* Check that the target method was invoked, but that the transaction
* infrastructure exception was thrown to the client
*/
@Test
public void cannotCommitTransaction() throws Exception {
TransactionAttribute txatt = new DefaultTransactionAttribute();
Method m = setNameMethod;
MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
tas.register(m, txatt);
// Method m2 = getNameMethod;
// No attributes for m2
PlatformTransactionManager ptm = mock(PlatformTransactionManager.clreplaced);
TransactionStatus status = mock(TransactionStatus.clreplaced);
given(ptm.getTransaction(txatt)).willReturn(status);
UnexpectedRollbackException ex = new UnexpectedRollbackException("foobar", null);
willThrow(ex).given(ptm).commit(status);
TestBean tb = new TestBean();
ITestBean itb = (ITestBean) advised(tb, ptm, tas);
String name = "new name";
try {
itb.setName(name);
fail("Shouldn't have succeeded");
} catch (UnexpectedRollbackException thrown) {
replacedertTrue(thrown == ex);
}
// Should have invoked target and changed name
replacedertTrue(itb.getName() == name);
}
17
View Source File : JpaNoRollbackTest.java
License : Apache License 2.0
Project Creator : micronaut-projects
License : Apache License 2.0
Project Creator : micronaut-projects
@AfterAll
void cleanup() {
final TransactionStatus tx = transactionManager.getTransaction(new DefaultTransactionDefinition());
final CriteriaBuilder criteriaBuilder = enreplacedyManager.getCriteriaBuilder();
final CriteriaDelete<Book> delete = criteriaBuilder.createCriteriaDelete(Book.clreplaced);
delete.from(Book.clreplaced);
enreplacedyManager.createQuery(delete).executeUpdate();
transactionManager.commit(tx);
}
17
View Source File : PlatformTransactionManagerFacade.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Override
public TransactionStatus getTransaction(TransactionDefinition definition) {
return delegate.getTransaction(definition);
}
17
View Source File : MicroTMProxy.java
License : Apache License 2.0
Project Creator : jeffreyning
License : Apache License 2.0
Project Creator : jeffreyning
@Override
public Object invoke(Object proxy, Method method0, Object[] args) throws Throwable {
String methodName = (String) args[0];
Object[] paramArray = (Object[]) args[1];
Method method = null;
try {
method = checkMethod(methodName, paramArray, oldGroovyObj.getClreplaced().getDeclaredMethods());
} catch (Exception e) {
}
boolean tranFlag = false;
Transactional trans = null;
if (method != null) {
trans = method.getAnnotation(Transactional.clreplaced);
if (trans != null) {
tranFlag = true;
}
}
if (tranFlag == true) {
// support info
String supportName = "";
if (proxy instanceof MicroServiceTemplateSupport) {
supportName = ((MicroServiceTemplateSupport) proxy).getDbName();
}
// change info
GroovyDataSource changeDataSource = method.getAnnotation(GroovyDataSource.clreplaced);
String changeName = "";
String oldName = "";
boolean changeFlag = false;
boolean pushFlag = false;
if (changeDataSource != null) {
changeFlag = true;
changeName = changeDataSource.name();
oldName = changeDataSource.name();
}
if (oldName == null || "".equals(oldName)) {
oldName = supportName;
}
// tran info
String dbName = "";
String beanId = trans.value();
PlatformTransactionManager transactionManager = null;
if (beanId != null && !"".equals(beanId)) {
transactionManager = (PlatformTransactionManager) MicroContextHolder.getContext().getBean(beanId);
} else {
if (changeFlag == false) {
dbName = supportName;
} else {
dbName = changeName;
}
if (dbName == null || "".equals(dbName)) {
dbName = "default";
}
transactionManager = MicroTranManagerHolder.getTransactionManager(dbName);
}
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setIsolationLevel(trans.isolation().value());
def.setPropagationBehavior(trans.propagation().value());
TransactionStatus status = transactionManager.getTransaction(def);
try {
Object retObj = method0.invoke(groovyObj, args);
transactionManager.commit(status);
return retObj;
} catch (Exception ex) {
transactionManager.rollback(status);
throw new RuntimeException(ex);
}
} else {
Object retObj = method0.invoke(groovyObj, args);
return retObj;
}
}
17
View Source File : GroovyTMAopImpl.java
License : Apache License 2.0
Project Creator : jeffreyning
License : Apache License 2.0
Project Creator : jeffreyning
public Object invokeMethod(GroovyObject groovyObject, String GroovyName, String methodName, Object... param) {
Clreplaced[] paramTypeArray = null;
if (param != null) {
int size = param.length;
paramTypeArray = new Clreplaced[size];
for (int i = 0; i < size; i++) {
paramTypeArray[i] = param[i].getClreplaced();
}
}
Method method = null;
try {
method = groovyObject.getClreplaced().getDeclaredMethod(methodName, paramTypeArray);
} catch (Exception e) {
}
boolean tranFlag = false;
Transactional trans = null;
if (method != null) {
trans = method.getAnnotation(Transactional.clreplaced);
if (trans != null) {
tranFlag = true;
}
}
if (tranFlag == true) {
// support info
String supportName = "";
if (groovyObject instanceof MicroServiceTemplateSupport) {
supportName = ((MicroServiceTemplateSupport) groovyObject).getDbName();
}
// change info
GroovyDataSource changeDataSource = method.getAnnotation(GroovyDataSource.clreplaced);
String changeName = "";
String oldName = "";
boolean changeFlag = false;
boolean pushFlag = false;
if (changeDataSource != null) {
changeFlag = true;
changeName = changeDataSource.name();
oldName = changeDataSource.name();
}
if (oldName == null || "".equals(oldName)) {
oldName = supportName;
}
// tran info
String dbName = "";
String beanId = trans.value();
PlatformTransactionManager transactionManager = null;
if (beanId != null && !"".equals(beanId)) {
transactionManager = (PlatformTransactionManager) MicroContextHolder.getContext().getBean(beanId);
} else {
if (changeFlag == false) {
dbName = supportName;
} else {
dbName = changeName;
}
if (dbName == null || "".equals(dbName)) {
dbName = "default";
}
transactionManager = MicroTranManagerHolder.getTransactionManager(dbName);
}
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setIsolationLevel(trans.isolation().value());
def.setPropagationBehavior(trans.propagation().value());
TransactionStatus status = transactionManager.getTransaction(def);
try {
// Object retObj= groovyObject.invokeMethod(methodName, param);
Object retObj = execNextHandler(groovyObject, GroovyName, methodName, param);
transactionManager.commit(status);
return retObj;
} catch (Exception ex) {
transactionManager.rollback(status);
throw new RuntimeException(ex);
}
} else {
// Object retObj=groovyObject.invokeMethod(methodName, param);
Object retObj = execNextHandler(groovyObject, GroovyName, methodName, param);
return retObj;
}
}
17
View Source File : StartTxTransactionHandler.java
License : GNU Lesser General Public License v3.0
Project Creator : dromara
License : GNU Lesser General Public License v3.0
Project Creator : dromara
@Override
public Object handler(final ProceedingJoinPoint point, final TxTransactionInfo info) throws Throwable {
LogUtil.info(LOGGER, "tx-transaction start, clreplaced:{}", () -> point.getTarget().getClreplaced());
final String groupId = IdWorkerUtils.getInstance().createGroupId();
// 设置事务组ID
TxTransactionLocal.getInstance().setTxGroupId(groupId);
final String waitKey = IdWorkerUtils.getInstance().createTaskKey();
String commitStatus = CommonConstant.TX_TRANSACTION_COMMIT_STATUS_BAD;
// 创建事务组信息
final Boolean success = txManagerMessageService.saveTxTransactionGroup(newTxTransactionGroup(groupId, waitKey, info));
if (success) {
// 如果发起方没有事务
if (info.getPropagationEnum().getValue() == PropagationEnum.PROPAGATION_NEVER.getValue()) {
try {
final Object res = point.proceed();
final Boolean commit = txManagerMessageService.preCommitTxTransaction(groupId);
if (commit) {
// 通知tm完成事务
CompletableFuture.runAsync(() -> txManagerMessageService.asyncCompleteCommit(groupId, waitKey, TransactionStatusEnum.COMMIT.getCode(), res));
}
return res;
} catch (Throwable throwable) {
// 通知tm整个事务组失败,需要回滚,(回滚那些正常提交的模块,他们正在等待通知。。。。)
txManagerMessageService.rollBackTxTransaction(groupId);
throwable.printStackTrace();
throw throwable;
}
}
PlatformTransactionManager platformTransactionManager = TransactionManagerHelper.getTransactionManager(info.getTransactionManager());
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def);
try {
// 发起调用
final Object res = point.proceed();
// 保存本地补偿数据
String compensateId = txCompensationManager.saveTxCompensation(info.getInvocation(), groupId, waitKey);
final Boolean commit = txManagerMessageService.preCommitTxTransaction(groupId);
if (commit) {
// 我觉得到这一步了,应该是切面走完,然后需要提交了,此时应该都是进行提交的
// 提交事务
platformTransactionManager.commit(transactionStatus);
// 通知tm完成事务
CompletableFuture.runAsync(() -> txManagerMessageService.asyncCompleteCommit(groupId, waitKey, TransactionStatusEnum.COMMIT.getCode(), res));
} else {
LogUtil.error(LOGGER, () -> "预提交失败!");
// 这里建议不直接删除补偿信息,交由补偿任务控制,当前任务无法判定提交超时还是返回失败
// txCompensationManager.removeTxCompensation(compensateId);
platformTransactionManager.rollback(transactionStatus);
}
// 删除补偿信息
txCompensationManager.removeTxCompensation(compensateId);
LogUtil.info(LOGGER, "tx-transaction end, clreplaced:{}", () -> point.getTarget().getClreplaced());
return res;
} catch (final Throwable throwable) {
// 如果有异常 当前项目事务进行回滚 ,同时通知tm 整个事务失败
platformTransactionManager.rollback(transactionStatus);
// 通知tm整个事务组失败,需要回滚,(回滚那些正常提交的模块,他们正在等待通知。。。。)
txManagerMessageService.rollBackTxTransaction(groupId);
// 通知tm 自身事务回滚
CompletableFuture.runAsync(() -> txManagerMessageService.asyncCompleteCommit(groupId, waitKey, TransactionStatusEnum.ROLLBACK.getCode(), null));
throwable.printStackTrace();
throw throwable;
} finally {
TxTransactionLocal.getInstance().removeTxGroupId();
/**
* 1. 若事务提交成功这里不进行处理,此时completeFlag="0" ,则异常情况下进入补偿的任务认为当前任务还在处理中,不对其进行补偿处理;
* 2. 若事务未提交,当前任务更新completeFlag="1" ,补偿任务可以继续向下执行补偿
*/
/*if (CommonConstant.TX_TRANSACTION_COMMIT_STATUS_BAD.equals(commitStatus)) {
txCompensationManager.updateTxCompensation(groupId);
}*/
}
} else {
throw new TransactionRuntimeException("TxManager connection ex!");
}
}
17
View Source File : WinnerServiceIsolationTest.java
License : Apache License 2.0
Project Creator : csj4032
License : Apache License 2.0
Project Creator : csj4032
@Test
@Order(8)
@DisplayName("SERIALIZABLE_INSERT")
public void serializable_read_insert() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setName("SERIALIZABLE");
definition.setPropagationBehavior(0);
definition.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
SqlSession localSqlSession = sqlSessionFactory.openSession();
TransactionStatus status = transactionManager.getTransaction(definition);
List<Winner> beforeWinnerList = localSqlSession.getMapper(WinnerMapper.clreplaced).findByIdGt(0);
DefaultTransactionDefinition definition2 = new DefaultTransactionDefinition();
definition2.setName("SERIALIZABLE_INSERT");
definition2.setPropagationBehavior(3);
TransactionStatus status2 = transactionManager.getTransaction(definition2);
SqlSession localSqlSession2 = sqlSessionFactory.openSession();
WinnerMapper localWinnerMapper = localSqlSession2.getMapper(WinnerMapper.clreplaced);
localWinnerMapper.insertWinner(Winner.builder().id(5).userId(5).winner(WinnerType.WINNER).regDt(LocalDateTime.now()).build());
localWinnerMapper.insertWinner(Winner.builder().id(6).userId(6).winner(WinnerType.WINNER).regDt(LocalDateTime.now()).build());
transactionManager.commit(status2);
localSqlSession.clearCache();
List<Winner> afterWinnerList = localSqlSession.getMapper(WinnerMapper.clreplaced).findByIdGt(0);
transactionManager.commit(status);
replacedertions.replacedertEquals(beforeWinnerList.size(), afterWinnerList.size());
}
17
View Source File : WinnerServiceIsolationTest.java
License : Apache License 2.0
Project Creator : csj4032
License : Apache License 2.0
Project Creator : csj4032
@Test
@Order(7)
@DisplayName("REPEATABLE_READ_REPEATABLE_READ_INSERT")
public void repeatable_read_insert() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setName("REPEATABLE_READ_REPEATABLE_READ_INSERT");
definition.setPropagationBehavior(0);
definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
definition.setReadOnly(true);
TransactionStatus status = transactionManager.getTransaction(definition);
SqlSession localSqlSession = sqlSessionFactory.openSession();
int beforeWinnerList = localSqlSession.getMapper(WinnerMapper.clreplaced).findByIdGtCount(0);
DefaultTransactionDefinition definition2 = new DefaultTransactionDefinition();
definition2.setName("REPEATABLE_READ_REPEATABLE_READ_INSERT_INSERT");
definition2.setPropagationBehavior(3);
definition2.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
TransactionStatus status2 = transactionManager.getTransaction(definition2);
SqlSession localSqlSession2 = sqlSessionFactory.openSession();
WinnerMapper localWinnerMapper = localSqlSession2.getMapper(WinnerMapper.clreplaced);
localWinnerMapper.insertWinner(Winner.builder().id(3).userId(3).winner(WinnerType.LOSER).regDt(LocalDateTime.now()).build());
localWinnerMapper.insertWinner(Winner.builder().id(4).userId(4).winner(WinnerType.LOSER).regDt(LocalDateTime.now()).build());
transactionManager.commit(status2);
localSqlSession.clearCache();
int afterWinnerList = localSqlSession.getMapper(WinnerMapper.clreplaced).findByIdGtCount(0);
transactionManager.commit(status);
replacedertions.replacedertNotEquals(beforeWinnerList, afterWinnerList);
}
17
View Source File : WinnerServiceIsolationTest.java
License : Apache License 2.0
Project Creator : csj4032
License : Apache License 2.0
Project Creator : csj4032
@Test
@Order(3)
@DisplayName("READ_UNCOMMITTED_SELECT")
public void read_uncommitted() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setName("READ_COMMITTED_SELECT");
definition.setPropagationBehavior(0);
definition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
TransactionStatus status = transactionManager.getTransaction(definition);
SqlSession localSqlSession = sqlSessionFactory.openSession();
WinnerMapper winnerMapper = localSqlSession.getMapper(WinnerMapper.clreplaced);
List<Winner> winnerList = winnerMapper.findAll();
transactionManager.commit(status);
replacedertions.replacedertFalse(winnerList.isEmpty());
}
17
View Source File : WinnerServiceIsolationTest.java
License : Apache License 2.0
Project Creator : csj4032
License : Apache License 2.0
Project Creator : csj4032
@Test
@Order(6)
@DisplayName("REPEATABLE_READ_REPEATABLE_READ")
public void repeatable_read_select() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setName("REPEATABLE_READ_REPEATABLE_READ");
definition.setPropagationBehavior(0);
definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
TransactionStatus status = transactionManager.getTransaction(definition);
SqlSession localSqlSession = sqlSessionFactory.openSession();
Winner before = localSqlSession.getMapper(WinnerMapper.clreplaced).findById(1);
DefaultTransactionDefinition definition2 = new DefaultTransactionDefinition();
definition2.setName("REPEATABLE_READ_REPEATABLE_READ_UPDATE");
definition2.setPropagationBehavior(3);
TransactionStatus status2 = transactionManager.getTransaction(definition2);
SqlSession localSqlSession2 = sqlSessionFactory.openSession();
WinnerMapper localWinnerMapper = localSqlSession2.getMapper(WinnerMapper.clreplaced);
localWinnerMapper.updateWinner(Winner.builder().id(1).userId(1).winner(WinnerType.LOSER).regDt(LocalDateTime.now()).build());
transactionManager.commit(status2);
localSqlSession.clearCache();
Winner after = localSqlSession.getMapper(WinnerMapper.clreplaced).findById(1);
transactionManager.commit(status);
replacedertions.replacedertEquals(before.getWinner(), after.getWinner());
}
17
View Source File : WinnerServiceIsolationTest.java
License : Apache License 2.0
Project Creator : csj4032
License : Apache License 2.0
Project Creator : csj4032
@Test
@Order(5)
@DisplayName("REPEATABLE_READ_READ_COMMITTED")
public void read_committed_repeatable() throws SQLException {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setName("REPEATABLE_READ_READ_COMMITTED");
definition.setPropagationBehavior(0);
definition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
TransactionStatus status = transactionManager.getTransaction(definition);
SqlSession localSqlSession = sqlSessionFactory.openSession();
Winner before = localSqlSession.getMapper(WinnerMapper.clreplaced).findById(1);
DefaultTransactionDefinition definition2 = new DefaultTransactionDefinition();
definition2.setName("REPEATABLE_READ_READ_COMMITTED_UPDATE");
definition2.setPropagationBehavior(3);
TransactionStatus status2 = transactionManager.getTransaction(definition2);
SqlSession localSqlSession2 = sqlSessionFactory.openSession();
WinnerMapper localWinnerMapper = localSqlSession2.getMapper(WinnerMapper.clreplaced);
localWinnerMapper.updateWinner(Winner.builder().id(1).winner(WinnerType.WINNER).regDt(LocalDateTime.now()).build());
transactionManager.commit(status2);
localSqlSession.clearCache();
Winner after = localSqlSession.getMapper(WinnerMapper.clreplaced).findById(1);
transactionManager.commit(status);
replacedertions.replacedertNotEquals(before.getWinner(), after.getWinner());
}
16
View Source File : Transaction.java
License : GNU General Public License v3.0
Project Creator : MoeraOrg
License : GNU General Public License v3.0
Project Creator : MoeraOrg
private static TransactionStatus beginTransaction(PlatformTransactionManager txManager) {
if (txManager == null) {
return null;
}
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
return txManager.getTransaction(definition);
}
16
View Source File : SpringHibernateDataStore.java
License : Apache License 2.0
Project Creator : illyasviel
License : Apache License 2.0
Project Creator : illyasviel
@Override
public DataStoreTransaction beginTransaction() {
// begin a spring transaction
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("elide transaction");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus txStatus = txManager.getTransaction(def);
Session session = enreplacedyManager.unwrap(Session.clreplaced);
Preconditions.checkNotNull(session);
return transactionSupplier.get(session, txManager, txStatus, isScrollEnabled, scrollMode);
}
16
View Source File : PlatformTxManagerUserDao.java
License : Apache License 2.0
Project Creator : Illusionist80
License : Apache License 2.0
Project Creator : Illusionist80
public int insertUser(final User user) {
TransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition();
TransactionStatus status = platformTransactionManager.getTransaction(paramTransactionDefinition);
String inserQuery = "insert into users (username, preplacedword, enabled , id) values (?, ?, ?, ?) ";
Object[] params = new Object[] { user.getUserName(), user.getPreplacedword(), user.isEnabled(), user.getId() };
int[] types = new int[] { Types.VARCHAR, Types.VARCHAR, Types.BIT, Types.INTEGER };
int rowsAffected = jdbcTemplate.update(inserQuery, params, types);
platformTransactionManager.commit(status);
return rowsAffected;
}
16
View Source File : WxOrderController.java
License : MIT License
Project Creator : geekyouth
License : MIT License
Project Creator : geekyouth
/**
* 取消订单
* 1. 检测当前订单是否能够取消
* 2. 设置订单取消状态
* 3. 商品货品数量增加
*
* @param userId 用户ID
* @param body 订单信息,{ orderId:xxx }
* @return 订单操作结果
* 成功则 { errno: 0, errmsg: '成功' }
* 失败则 { errno: XXX, errmsg: XXX }
*/
@PostMapping("cancel")
public Object cancel(@LoginUser Integer userId, @RequestBody String body) {
if (userId == null) {
return ResponseUtil.unlogin();
}
Integer orderId = JacksonUtil.parseInteger(body, "orderId");
if (orderId == null) {
return ResponseUtil.badArgument();
}
LitemallOrder order = orderService.findById(orderId);
if (order == null) {
return ResponseUtil.badArgumentValue();
}
if (!order.getUserId().equals(userId)) {
return ResponseUtil.badArgumentValue();
}
// 检测是否能够取消
OrderHandleOption handleOption = OrderUtil.build(order);
if (!handleOption.isCancel()) {
return ResponseUtil.fail(403, "订单不能取消");
}
// 开启事务管理
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
try {
// 设置订单已取消状态
order.setOrderStatus(OrderUtil.STATUS_CANCEL);
order.setEndTime(LocalDateTime.now());
orderService.update(order);
// 商品货品数量增加
List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
for (LitemallOrderGoods orderGoods : orderGoodsList) {
Integer productId = orderGoods.getProductId();
LitemallProduct product = productService.findById(productId);
Integer number = product.getNumber() + orderGoods.getNumber();
product.setNumber(number);
productService.updateById(product);
}
} catch (Exception ex) {
txManager.rollback(status);
logger.error("系统内部错误", ex);
return ResponseUtil.fail(403, "订单取消失败");
}
txManager.commit(status);
return ResponseUtil.ok();
}
16
View Source File : AdminGoodsController.java
License : MIT License
Project Creator : geekyouth
License : MIT License
Project Creator : geekyouth
@PostMapping("/delete")
public Object delete(@LoginAdmin Integer adminId, @RequestBody LitemallGoods goods) {
if (adminId == null) {
return ResponseUtil.unlogin();
}
// 开启事务管理
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
try {
Integer gid = goods.getId();
goodsService.deleteById(gid);
specificationService.deleteByGid(gid);
attributeService.deleteByGid(gid);
productService.deleteByGid(gid);
} catch (Exception ex) {
txManager.rollback(status);
logger.error("系统内部错误", ex);
}
txManager.commit(status);
return ResponseUtil.ok();
}
15
View Source File : TransactionalProducerImpl.java
License : Apache License 2.0
Project Creator : open-hand
License : Apache License 2.0
Project Creator : open-hand
@Override
public void apply(StartSagaBuilder builder, Consumer<StartSagaBuilder> consumer, TransactionDefinition definition) {
String uuid = generateUUID();
TransactionStatus status = transactionManager.getTransaction(definition);
builder.withUuid(uuid).withService(service);
try {
sagaClient.preCreateSaga(builder.preBuild());
consumer.accept(builder);
consistencyHandler.beforeTransactionCommit(uuid, builder.confirmBuild());
transactionManager.commit(status);
} catch (Exception e) {
consistencyHandler.beforeTransactionCancel(uuid);
transactionManager.rollback(status);
sagaClient.cancelSaga(uuid);
throw e;
}
sagaClient.confirmSaga(uuid, builder.confirmBuild());
}
15
View Source File : TransactionalProducerImpl.java
License : Apache License 2.0
Project Creator : open-hand
License : Apache License 2.0
Project Creator : open-hand
@Override
public <T> T applyAndReturn(StartSagaBuilder builder, Function<StartSagaBuilder, T> function, TransactionDefinition definition) {
T result;
String uuid = generateUUID();
TransactionStatus status = transactionManager.getTransaction(definition);
builder.withUuid(uuid).withService(service);
try {
// 解决TransactionalProducer.applyAndReturn() function中设置 sourceId不生效问题
result = function.apply(builder);
sagaClient.preCreateSaga(builder.preBuild());
consistencyHandler.beforeTransactionCommit(uuid, builder.confirmBuild());
transactionManager.commit(status);
} catch (Exception e) {
consistencyHandler.beforeTransactionCancel(uuid);
transactionManager.rollback(status);
sagaClient.cancelSaga(uuid);
throw e;
}
sagaClient.confirmSaga(uuid, builder.confirmBuild());
return result;
}
15
View Source File : TransactionAwareCacheDecoratorTests.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Test
public void putTransactional() {
Cache target = new ConcurrentMapCache("testCache");
Cache cache = new TransactionAwareCacheDecorator(target);
TransactionStatus status = txManager.getTransaction(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
Object key = new Object();
cache.put(key, "123");
replacedertNull(target.get(key));
txManager.commit(status);
replacedertEquals("123", target.get(key, String.clreplaced));
}
15
View Source File : AdminOrderController.java
License : MIT License
Project Creator : geekyouth
License : MIT License
Project Creator : geekyouth
/**
* 自动取消订单
* <p>
* 定时检查订单未付款情况,如果超时半个小时则自动取消订单
* 定时时间是每次相隔半个小时。
* <p>
* 注意,因为是相隔半小时检查,因此导致有订单是超时一个小时以后才设置取消状态。
* TODO
* 这里可以进一步地配合用户订单查询时订单未付款检查,如果订单超时半小时则取消。
*/
@Scheduled(fixedDelay = 30 * 60 * 1000)
public void checkOrderUnpaid() {
logger.debug(LocalDateTime.now());
List<LitemallOrder> orderList = orderService.queryUnpaid();
for (LitemallOrder order : orderList) {
LocalDateTime add = order.getAddTime();
LocalDateTime now = LocalDateTime.now();
LocalDateTime expired = add.plusMinutes(30);
if (expired.isAfter(now)) {
continue;
}
// 开启事务管理
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
try {
// 设置订单已取消状态
order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
order.setEndTime(LocalDateTime.now());
orderService.updateById(order);
// 商品货品数量增加
Integer orderId = order.getId();
List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
for (LitemallOrderGoods orderGoods : orderGoodsList) {
Integer productId = orderGoods.getProductId();
LitemallProduct product = productService.findById(productId);
Integer number = product.getNumber() + orderGoods.getNumber();
product.setNumber(number);
productService.updateById(product);
}
} catch (Exception ex) {
txManager.rollback(status);
logger.error("系统内部错误", ex);
}
txManager.commit(status);
}
}
15
View Source File : StartCompensationHandler.java
License : GNU Lesser General Public License v3.0
Project Creator : dromara
License : GNU Lesser General Public License v3.0
Project Creator : dromara
/**
* 补偿的时候,不走分布式事务处理.
*
* @param point point 切点
* @param info 信息
* @return Object
* @throws Throwable ex
*/
@Override
public Object handler(final ProceedingJoinPoint point, final TxTransactionInfo info) throws Throwable {
TxTransactionLocal.getInstance().setTxGroupId(CommonConstant.COMPENSATE_ID);
PlatformTransactionManager platformTransactionManager = TransactionManagerHelper.getTransactionManager(info.getTransactionManager());
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def);
try {
final Object proceed = point.proceed();
platformTransactionManager.commit(transactionStatus);
return proceed;
} catch (Throwable e) {
platformTransactionManager.rollback(transactionStatus);
throw e;
} finally {
TxTransactionLocal.getInstance().removeTxGroupId();
CompensationLocal.getInstance().removeCompensationId();
}
}
15
View Source File : InsideCompensationHandler.java
License : GNU Lesser General Public License v3.0
Project Creator : dromara
License : GNU Lesser General Public License v3.0
Project Creator : dromara
/**
* 处理补偿内嵌的远程方法的时候,不提交,只调用.
*
* @param point point 切点
* @param info 信息
* @return Object
* @throws Throwable 异常
*/
@Override
public Object handler(final ProceedingJoinPoint point, final TxTransactionInfo info) throws Throwable {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
PlatformTransactionManager platformTransactionManager = TransactionManagerHelper.getTransactionManager(info.getTransactionManager());
TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def);
try {
return point.proceed();
} finally {
platformTransactionManager.rollback(transactionStatus);
}
}
15
View Source File : PersistHelper.java
License : Apache License 2.0
Project Creator : alibaba
License : Apache License 2.0
Project Creator : alibaba
private TransactionStatus getTransactionStatus() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
return transactionManager.getTransaction(definition);
}
14
View Source File : TransactionalTestExecutionListenerTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
private void replacedertAfterTestMethodWithTransactionalTestMethod(Clreplaced<? extends Invocable> clazz) throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(clazz);
Invocable instance = BeanUtils.instantiateClreplaced(clazz);
given(testContext.getTestInstance()).willReturn(instance);
given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest"));
given(tm.getTransaction(BDDMockito.any(TransactionDefinition.clreplaced))).willReturn(new SimpleTransactionStatus());
replacedertFalse("callback should not have been invoked", instance.invoked());
TransactionContextHolder.removeCurrentTransactionContext();
listener.beforeTestMethod(testContext);
replacedertFalse("callback should not have been invoked", instance.invoked());
listener.afterTestMethod(testContext);
replacedertTrue("callback should have been invoked", instance.invoked());
}
14
View Source File : TransactionalTestExecutionListenerTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
private void replacedertAfterTestMethodWithTransactionalTestMethod(Clreplaced<? extends Invocable> clazz) throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(clazz);
Invocable instance = BeanUtils.instantiateClreplaced(clazz);
given(testContext.getTestInstance()).willReturn(instance);
given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest"));
given(tm.getTransaction(BDDMockito.any(TransactionDefinition.clreplaced))).willReturn(new SimpleTransactionStatus());
replacedertThat(instance.invoked()).as("callback should not have been invoked").isFalse();
TransactionContextHolder.removeCurrentTransactionContext();
listener.beforeTestMethod(testContext);
replacedertThat(instance.invoked()).as("callback should not have been invoked").isFalse();
listener.afterTestMethod(testContext);
replacedertThat(instance.invoked()).as("callback should have been invoked").isTrue();
}
See More Examples