Ну ... попытался найти в Google и здесь, но потерпел неудачу. Вот моя история: < /p>
Spring Mvc 3.1.1 Release < /li>
Данные пружины JPA 1.1.0 Выпуск < /li>
Hibernate 3.6.9.final < /li>
< /ul>
Другие выводы:
1) Когда я аннотирую метод @transactional из другой службы, создается транзакция. < /P>
21:49:13.397 [DEBUG] (http-8080-2) org.springframework.orm.jpa.JpaTransactionManager - Creating new transaction with name [com.xen.components.page.PageServiceImpl.findAllOrdered]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
< /code>
2) Служба, в которой этот метод находится обернутым с прокси (я видел в отладке) и метод, вызываемый от контроллера, поэтому вызов проходит через прокси.
3) обе службы в корневом контексте приложения. Вывод log.error (контекст): < /p>
OrderServiceImpl - Root WebApplicationContext: startup date [Tue Sep 17 21:48:30 FET 2013]; root of context hierarchy
PageServiceImpl - Root WebApplicationContext: startup date [Tue Sep 17 21:48:30 FET 2013]; root of context hierarchy
< /code>
Вот код метода: < /p>
@Service
public class OrderServiceImpl extends CRUDServiceImpl implements OrderService {
private static final Logger log = Logger.getLogger(OrderServiceImpl.class);
@Autowired
private OrderRepository repo;
@Autowired
private OrderItemService orderItemService;
@Override
protected CRUDRepository getRepository() {
return repo;
}
@Override
@Transactional(propagation=Propagation.REQUIRES_NEW)
public Order save(Order entity) {
if (entity.getCreationDate() == null) {
entity.setCreationDate(new Date());
}
if (entity.getId() == null) {
increasePopularityForProductsInOrder(entity);
// throws NoTransactionException: No transaction aspect-managed TransactionStatus in scope
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
decreaseStockNumberForSkusInOrder(entity);
}
return super.save(entity);
}
private void increasePopularityForProductsInOrder(Order order) {
List items = order.getItems();
for (OrderItem item : items) {
orderItemService.increasePopularity(item);
}
}
private void decreaseStockNumberForSkusInOrder(Order order) {
List items = order.getItems();
for (OrderItem item : items) {
orderItemService.removeFromStock(item);
}
}
}
< /code>
Этот метод вызывается от контроллера. Код контроллера прост, только валидация и orderservice.save (...) call.
Вот мой конфигурация: < /p>
ApplicationContext.xml>
< /code>
servletcontext.xml
< /p>
404
404
/WEB-INF/layouts/layouts.xml
/WEB-INF/views/**/views.xml
< /code>
persistence.xml
org.hibernate.ejb.HibernatePersistence
< /code>
Обновление:
cartcontroller.java
@Controller
public class CartController {
private static final Logger log = Logger.getLogger(CartController.class);
...
@RequestMapping(value = "/cart/submit-order", method = RequestMethod.POST)
public String submit(@RequestParam String email, @RequestParam long deliveryType, Model uiModel, HttpServletRequest request, RedirectAttributes redirectAttrs) {
Order order = CartHelper.getOrderFromRequest(request);
uiModel.addAttribute("email", email);
// 1. check if address is set
if (StringUtil.isEmpty(order.getClientInfo().getFirstName())) {
MessageBean.createErrorMessage("cart.enter-address.error").displayMessage(uiModel);
populateForm(uiModel, order);
return "cart";
}
// 2. check if specified deliveryType exist
DeliveryType type = null;
try {
type = deliveryTypeService.findOne(deliveryType);
} catch (NotFoundException nfe) {
MessageBean.createErrorMessage("cart.invalid-delivery-type.error").displayMessage(uiModel);
populateForm(uiModel, order);
return "cart";
}
order.setDeliveryType(type);
// 3. check if email is valid
if (!StringUtil.isEmailValid(email)) {
MessageBean.createErrorMessage("cart.invalid-email.error").displayMessage(uiModel);
populateForm(uiModel, order);
return "cart";
}
order.getClientInfo().setEmail(email);
// 4. check if order is not empty
if (order.isEmpty()) { // should not be possible
log.warn("Empty order submission registered! " + order);
return "cart/empty";
}
order = orderService.save(order);
CartHelper.updateOrderForRequest(request, order);
// 5. send notification to client
try {
sendNotificationToClient(order, request);
redirectAttrs.addFlashAttribute(MessageBean.MESSAGE_BEAN_KEY, MessageBean.createSuccessMessage("cart.order.successfuly.created"));
} catch (Exception e) {
redirectAttrs.addFlashAttribute(MessageBean.MESSAGE_BEAN_KEY, MessageBean.createErrorMessage("cart.failed.to.send.notification.during.order.saving"));
}
return "redirect:/orders/success";
}
...
}
< /code>
Если у вас есть какие -либо мысли, пожалуйста, опубликуйте это. Я схожу с ума от этого.
Подробнее здесь: https://stackoverflow.com/questions/188 ... not-create
@transactional аннотированный класс, завернутый в прокси, но транзакция не создана ⇐ JAVA
Программисты JAVA общаются здесь
1758093115
Anonymous
Ну ... попытался найти в Google и здесь, но потерпел неудачу. Вот моя история: < /p>
Spring Mvc 3.1.1 Release < /li>
Данные пружины JPA 1.1.0 Выпуск < /li>
Hibernate 3.6.9.final < /li>
< /ul>
Другие выводы:
1) Когда я аннотирую метод @transactional из другой службы, создается транзакция. < /P>
21:49:13.397 [DEBUG] (http-8080-2) org.springframework.orm.jpa.JpaTransactionManager - Creating new transaction with name [com.xen.components.page.PageServiceImpl.findAllOrdered]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
< /code>
2) Служба, в которой этот метод находится обернутым с прокси (я видел в отладке) и метод, вызываемый от контроллера, поэтому вызов проходит через прокси.
3) обе службы в корневом контексте приложения. Вывод log.error (контекст): < /p>
OrderServiceImpl - Root WebApplicationContext: startup date [Tue Sep 17 21:48:30 FET 2013]; root of context hierarchy
PageServiceImpl - Root WebApplicationContext: startup date [Tue Sep 17 21:48:30 FET 2013]; root of context hierarchy
< /code>
Вот код метода: < /p>
@Service
public class OrderServiceImpl extends CRUDServiceImpl implements OrderService {
private static final Logger log = Logger.getLogger(OrderServiceImpl.class);
@Autowired
private OrderRepository repo;
@Autowired
private OrderItemService orderItemService;
@Override
protected CRUDRepository getRepository() {
return repo;
}
@Override
@Transactional(propagation=Propagation.REQUIRES_NEW)
public Order save(Order entity) {
if (entity.getCreationDate() == null) {
entity.setCreationDate(new Date());
}
if (entity.getId() == null) {
increasePopularityForProductsInOrder(entity);
// throws NoTransactionException: No transaction aspect-managed TransactionStatus in scope
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
decreaseStockNumberForSkusInOrder(entity);
}
return super.save(entity);
}
private void increasePopularityForProductsInOrder(Order order) {
List items = order.getItems();
for (OrderItem item : items) {
orderItemService.increasePopularity(item);
}
}
private void decreaseStockNumberForSkusInOrder(Order order) {
List items = order.getItems();
for (OrderItem item : items) {
orderItemService.removeFromStock(item);
}
}
}
< /code>
Этот метод вызывается от контроллера. Код контроллера прост, только валидация и orderservice.save (...) call.
Вот мой конфигурация: < /p>
ApplicationContext.xml>
< /code>
servletcontext.xml
< /p>
404
404
/WEB-INF/layouts/layouts.xml
/WEB-INF/views/**/views.xml
< /code>
persistence.xml
org.hibernate.ejb.HibernatePersistence
< /code>
Обновление:
cartcontroller.java
@Controller
public class CartController {
private static final Logger log = Logger.getLogger(CartController.class);
...
@RequestMapping(value = "/cart/submit-order", method = RequestMethod.POST)
public String submit(@RequestParam String email, @RequestParam long deliveryType, Model uiModel, HttpServletRequest request, RedirectAttributes redirectAttrs) {
Order order = CartHelper.getOrderFromRequest(request);
uiModel.addAttribute("email", email);
// 1. check if address is set
if (StringUtil.isEmpty(order.getClientInfo().getFirstName())) {
MessageBean.createErrorMessage("cart.enter-address.error").displayMessage(uiModel);
populateForm(uiModel, order);
return "cart";
}
// 2. check if specified deliveryType exist
DeliveryType type = null;
try {
type = deliveryTypeService.findOne(deliveryType);
} catch (NotFoundException nfe) {
MessageBean.createErrorMessage("cart.invalid-delivery-type.error").displayMessage(uiModel);
populateForm(uiModel, order);
return "cart";
}
order.setDeliveryType(type);
// 3. check if email is valid
if (!StringUtil.isEmailValid(email)) {
MessageBean.createErrorMessage("cart.invalid-email.error").displayMessage(uiModel);
populateForm(uiModel, order);
return "cart";
}
order.getClientInfo().setEmail(email);
// 4. check if order is not empty
if (order.isEmpty()) { // should not be possible
log.warn("Empty order submission registered! " + order);
return "cart/empty";
}
order = orderService.save(order);
CartHelper.updateOrderForRequest(request, order);
// 5. send notification to client
try {
sendNotificationToClient(order, request);
redirectAttrs.addFlashAttribute(MessageBean.MESSAGE_BEAN_KEY, MessageBean.createSuccessMessage("cart.order.successfuly.created"));
} catch (Exception e) {
redirectAttrs.addFlashAttribute(MessageBean.MESSAGE_BEAN_KEY, MessageBean.createErrorMessage("cart.failed.to.send.notification.during.order.saving"));
}
return "redirect:/orders/success";
}
...
}
< /code>
Если у вас есть какие -либо мысли, пожалуйста, опубликуйте это. Я схожу с ума от этого.
Подробнее здесь: [url]https://stackoverflow.com/questions/18858880/transactional-annotated-class-wrapped-with-proxy-but-transaction-is-not-create[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия