1

我在程序执行期间收到以下异常:

org.hibernate.ObjectDeletedException: deleted instance passed to merge: [ns.entity.Category#<null>]; nested exception is java.lang.IllegalArgumentException: org.hibernate.ObjectDeletedException: deleted instance passed to merge: [ns.entity.Category#<null>]

以下代码抛出异常:

importer.foo();

进口商服务:

@Service
@Transactional
public class Importer {

    @Autowired
    private UserService userService;

    @Autowired
    private CategoryService categoryService;

    @Transactional
    public void foo() {
        User user = userService.findByLogin("max");
        categoryService.delete(user.getCategories());
    }
}

用户服务(使用 CrudRepository):

@Service
@Repository
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository repository;

    @Override
    @Transactional(readOnly = true)
    public User findById(Long userId) {
        return repository.findOne(userId);
    }
}

CategoryService(使用 CrudRepository):

@Service
@Repository
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository repository;

    @Override
    @Transactional
    public void delete(Set<Category> categories) {
        repository.delete(categories);
    }
}

以下代码片段CategoryServiceImpl.delete()无一例外地有效:

  for (Category category : categories) {
      Category newCat = findById(category.getCategoryId());
      if (newCat != null) {
          delete(newCat);
      }
  }

据我了解,使用了两种不同的事务(一个只读,一个用于删除)。是否可以将事务重新用于所有调用?(readOnly = true)从中删除UserServiceImpl.findById()无济于事。

根据 Spring 文档,我认为所有三种方法(Importer.foo(), UserServiceImpl.findById(), )都应该只使用一个事务。CategoryServiceImpl.delete()

4

0 回答 0