1

I'm trying to understand, how does injecting of EntityManger in Spring bean work. I have bean

@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TestUpdateService {


    @PersistenceContext
    private EntityManager entityManager;

    private final OrderRepository orderRepository;

    @Transactional
    public void doWork(Long id) {
        Order order = orderRepository.findById(id).get();
        entityManager.detach(order);
        orderRepository.save(order);
    }
}

And have a couple of questions:

  1. Am I right that for every call of my transactional method doWork new instance of EntityManager will be created? I read (or mb misunderstood) on stackoverflow that entity manager annotated with @PersistanceContext creates own EntityManager for each transaction.
  2. If it is so, does @Autowired work the same way?
  3. If it isn't so, then how do these both annotations work?
Anish B.
  • 9,111
  • 3
  • 21
  • 41
  • Maybe this is link is helpful for you https://stackoverflow.com/questions/31335211/autowired-vs-persistencecontext-for-entitymanager-bean – SYED MUSTAFA HUSSAIN Apr 07 '21 at 16:12
  • @SyedMustafaHussain I read this question and now I'm trying to undestand if I got it right. That's why I asked these 3 questions – Vladimir Safonov Apr 07 '21 at 16:23
  • Does this answer your question? [@Autowired vs @PersistenceContext for EntityManager bean](https://stackoverflow.com/questions/31335211/autowired-vs-persistencecontext-for-entitymanager-bean) – Anish B. Apr 07 '21 at 17:06

0 Answers0