Donatello
Donatello

Reputation: 353

When should I use entityManager.flush() if i am already using @Transactional

I am using JPA in Spring Boot Application.

I am only getting starting to use It and I have some questions.

My DAO code is the following:

@Transactional
public class DatabaseUnitDao implements IDatabaseUnitDao {

@PersistenceContext
    private EntityManager entityManager;

@Override
    public void create(Unit unit) {
        final String CREATE_UNIT =
                "CREATE TABLE " + unit.getName() + " (id VARCHAR(255) PRIMARY KEY NOT NULL, value text NOT NULL)";
        entityManager.persist(unit);   // add an info about unit in the general table
        entityManager.createNativeQuery(CREATE_UNIT).executeUpdate(); // create table for this units
    }
}

1.Should I use flush() in this case?

2.Is It enough to just annotate DAO class with @Transactional?

Some resources tell that it's needed to use @EnableTransactionManagement to use @Transactional.

Upvotes: 0

Views: 147

Answers (1)

amseager
amseager

Reputation: 6391

  1. No. JPA provider has to do it for you at the end of the transactional method's invocation.

  2. Yes. Spring Boot enables transaction management by default (with proxyTargetClass = true)

Upvotes: 2

Related Questions