Can em do the work without being created as an entity manager in Spring Boot?

There is some code in front of me, And I am expected to find a mistake.

My team leader said that there is a procedure that gets data and fills the db. And told me to find the mistake

I am given a completed project, i found the procedure, its here ->

@Procedure(name = "SP_Order_Series_Multiplier")
double getMultiplierByCariKod(@Param("CariKod") String cariKod);

I found what it does here.

@Transactional
public Double getMultiplierByCariKod(String cariKod) {
    StoredProcedureQuery query = em.createNamedStoredProcedureQuery("SP_Order_Series_Multiplier");
    query.registerStoredProcedureParameter("CariKod", String.class, ParameterMode.IN);
    query.registerStoredProcedureParameter("Multiplier", Double.class, ParameterMode.OUT);
    query.setParameter("CariKod", cariKod);
    query.execute();
    return (Double) query.getOutputParameterValue("Multiplier");
}

I looked if em was created before but its only written as

@Autowired
EntityManager em;

I thought we should say something like that

EntityManager em = emf.createEntityManager(); 
em.getTransaction().begin();

And there is no code like

em.getTransaction().commit();
em.close();

Do you have any idea? Am i wrong?

Answer

There are two types of EntityManager:

  • Container-Managed – the container injects EntityManager for us.

    @PersistenceContext
    EntityManager entityManager;
    

    BTW, you shouldn’t use @Autowire to get the EM –

    @Autowired vs @PersistenceContext for EntityManager bean.

  • Application-Managed:

      EntityManager em = emf.createEntityManager(); 
    

    We should manage the lifecycle of the EntityManager we’ve created.

Also, the @Transactional already takes care of beginning the transaction, as well as committing.

Leave a Reply

Your email address will not be published. Required fields are marked *