Kevindra
Kevindra

Reputation: 1762

Spring Transaction is trying to fire update after select query

I have a DAO method which executes a simple select query:

@Transactional
public List<Object[]> getMyTableData(Long someId)
{
    Session session = (Session) getEntityManager().getDelegate();

    return session
        .createSQLQuery("SELECT * FROM my_table where some_id = :someId")
        .addEntity(MyTable.class)
        .setParameter("someId", someId)
        .list();
}

When I run it I find two queries in the logs:

  1. A "select * from MyTable where some_id = ..." query which gets the result successfully
  2. And after it I find this in my logs:

    org.springframework.orm.jpa.JpaTransactionManager: Initiating transaction commit org.springframework.orm.jpa.JpaTransactionManager: Committing JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@162add4] org.hibernate.transaction.JDBCTransaction: commit org.hibernate.event.def.AbstractFlushingEventListener: processing flush-time cascades org.hibernate.event.def.AbstractFlushingEventListener: Flushed: 0 insertions, 1 updates, 0 deletions to 2 objects

then it fires another query "Update my_table set .... "

Why is this update query getting executed?

Upvotes: 2

Views: 4535

Answers (1)

Kevindra
Kevindra

Reputation: 1762

As Pace mentioned above "In JPA when a transaction commits JPA will write any modified entities to the database". So I tried adding readOnly = true to the @Transactional annotation and it fixed the issue.

Upvotes: 2

Related Questions