java - Spring数据和play框架,spring不创建新事务

标签 java spring hibernate playframework-2.0 spring-data

在我的项目中,我得到了类别类别(仅重要部分代码):

class Category {
  @LazyCollection(LazyCollectionOption.EXTRA)
  @ManyToMany(mappedBy = "categories", cascade = CascadeType.REMOVE)
  private Set<Entity> entities = new HashSet<Entity>();
  /*.rest of code not necessary.*/
}

还有另一个与多对多相关的类:

class Entity {
  @LazyCollection(LazyCollectionOption.EXTRA)
  @ManyToMany(cascade = CascadeType.REMOVE)
  private Set<Category> categories;
  /*.rest of code not necessary.*/
}

我有一个类别 Controller ,我从中调用方法删除。类声明如下所示:

@Named
@Component
@Singleton
public class Categories extends Controller {

这是我的 Controller 中的方法:

public Result delete(Long id) {
  categoriesService.delete(id);
  return ok();
}

我有这样声明的categoryServiceImpl:

@Named
@Component
@Singleton
public class CategoriesServiceImpl implements CategoriesService {

以及service中没有事务的delete方法:

public void delete(Long id) {
  Category category = findById(id);
  boolean inTransaction = TransactionSynchronizationManager.isActualTransactionActive();

  Logger.info("Am I in transaction" + inTransaction);

  /* Exception while trying to access category.getEntities() */ 
  for(Entity entity : category.getEntities()) {
    entity.getCategories().remove(category);
    entityService.update(entity);
  }

  category.getEntities().clear();
  repo.delete(category);
}

我在服务删除方法中尝试访问category.getEntities()时遇到异常:

LazyInitializationException: failed to lazily initialize a collection of role: models.Category.entities, could not initialize proxy - no Session]

我知道这是因为这个方法中没有事务。但是,当我尝试强制事务到我的服务方法时,如下所示:

@Transactional(propagation = Propagation.MANDATORY)
public void delete(Long id) {

@Transactional(propagation = Propagation.REQUIRES_NEW)或任何传播枚举,我仍然没有在此方法中获得事务。

我做错了什么?我该如何解决它?无论如何,重构代码、另一种方法或想到的任何方法?

最佳答案

尝试使用

public void delete(Long id) {
   Category category = findById(id);
   Hibernate.initialize(category.brands);
   boolean inTransaction = TransactionSynchronizationManager.isActualTransactionActive();
   //Remaining Code Here

}

关于java - Spring数据和play框架,spring不创建新事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20092357/

相关文章:

java - MarkLogic PojoRepository 搜索范围日期不起作用

java - 如何将整数的小映射表示为数组?

java - 多注释验证检查序列

java - 如何在rest api中使用xml/json请求发送html内容?

hibernate - weblogic.management.ManagementException : There is the same running task.

hibernate - 如何使用 JPA CriteriaQuery 搜索子类属性?

postgresql - 使用@Query JPA 注释将空参数传递给 native 查询

java - Kerberos 与 Java

java - AbstractApplicationContext 尚未刷新异常

Spring JMS URL - 将 SSL 转换为 TCP