Search code examples
hibernategoogle-cloud-spanner

Switch read-only transaction and read-write transaction in google-cloud-spanner-hibernate


I want to switch read-write transaction and read-only transaction with google-cloud-spanner-hibernate.

In JPA, LockMode is set for each Query, but not for each Transaction. Is there any way to control it in google-cloud-spanner-hibernate?


Solution

  • I found a solution from the Hibernate forums which may help. If you're using native Hibernate, you can do something like this:

    Session session = sessionFactory.openSession();
    ((SessionImplementor)session).connection().setReadOnly(true);
    session.setHibernateFlushMode(FlushMode.MANUAL);
    
    session.beginTransaction();
    
    ... do your work ...
    
    session.commitTransaction();
    

    This will make the underlying connection use a read-only Spanner database transaction. The casting operation seems a little unusual... I'll followup and ask the Hibernate folks on what they recommend exactly but this can at least be a workaround. You can see similar casting operations done in the Spring HibernateTransactionManager, so maybe it is common practice.

    If you are using Spring, you will have access to a more elegant method - the @Transactional(readonly = true) annotation. More info here.