2
votes

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?

1
Most of that logging is indicating that your transaction is closing. Since the Transactional is around the getMyTableData() method it will begin a transaction before the method and close it at the end (unless the calling method is also annotated with Transactional in which case it will simply join the larger transaction). In JPA when a transaction commits JPA will write any modified entities to the database. The strange thing is in the example you've shown you haven't modified the results of the query at all. In your real application are you doing anything to the objects being returned? - Pace
No I did not update any thing in the result set. But I figured out that if you add "readOnly = true" in the transaction annotation it would not update your entities. - Kevindra

1 Answers

2
votes

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.