61 lines
2.4 KiB
Java
Executable File
61 lines
2.4 KiB
Java
Executable File
package com.ankurm.hibernatedemo;
|
|
|
|
import static org.assertj.core.api.Assertions.assertThat;
|
|
|
|
import com.ankurm.hibernatedemo.immutable.ExchangeRate;
|
|
import jakarta.persistence.EntityManager;
|
|
import jakarta.persistence.EntityManagerFactory;
|
|
import java.math.BigDecimal;
|
|
import org.junit.jupiter.api.Test;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.boot.test.context.SpringBootTest;
|
|
|
|
/**
|
|
* Backs docs/07-immutable-entities.md. A SEPARATE Spring context (own EntityManagerFactory) with
|
|
* {@code hibernate.query.immutable_entity_update_query_handling_mode=allow} set, to prove the
|
|
* escape hatch from {@link ImmutableEntityTest#bulkHqlUpdate_onImmutableEntity_isRejectedAtTranslationTime_byDefault}
|
|
* really lets the bulk HQL UPDATE run -- and that when it does, the UPDATE is issued for real.
|
|
* This is a SessionFactory-wide setting, not a per-query hint, hence the separate context.
|
|
*/
|
|
@SpringBootTest(properties = {
|
|
"spring.jpa.properties.hibernate.query.immutable_entity_update_query_handling_mode=allow"
|
|
})
|
|
class ImmutableBulkUpdateAllowedTest {
|
|
|
|
private static final Logger DEMO = LoggerFactory.getLogger("DEMO");
|
|
|
|
@Autowired
|
|
private EntityManagerFactory emf;
|
|
|
|
@Test
|
|
void withHandlingModeSetToAllow_bulkHqlUpdate_actuallyRunsAgainstImmutableEntity() {
|
|
EntityManager seed = emf.createEntityManager();
|
|
seed.getTransaction().begin();
|
|
ExchangeRate rate = new ExchangeRate("ZAR/USD", new BigDecimal("18.0000"));
|
|
seed.persist(rate);
|
|
seed.getTransaction().commit();
|
|
Long id = rate.getId();
|
|
seed.close();
|
|
|
|
EntityManager em = emf.createEntityManager();
|
|
em.getTransaction().begin();
|
|
int updated = em.createQuery("update ExchangeRate set rate = :r where id = :id")
|
|
.setParameter("r", new BigDecimal("1.0000"))
|
|
.setParameter("id", id)
|
|
.executeUpdate();
|
|
em.getTransaction().commit();
|
|
em.close();
|
|
DEMO.info("with handling-mode=allow, bulk HQL UPDATE rowsAffected={}", updated);
|
|
|
|
EntityManager verify = emf.createEntityManager();
|
|
ExchangeRate reloaded = verify.find(ExchangeRate.class, id);
|
|
DEMO.info("row after allowed bulk HQL update: {}", reloaded);
|
|
verify.close();
|
|
|
|
assertThat(updated).isEqualTo(1);
|
|
assertThat(reloaded.getRate()).isEqualByComparingTo("1.0000");
|
|
}
|
|
}
|