|
| 1 | +package org.hibernate.orm.test.deletedetached; |
| 2 | + |
| 3 | +import jakarta.persistence.Entity; |
| 4 | +import jakarta.persistence.GeneratedValue; |
| 5 | +import jakarta.persistence.Id; |
| 6 | +import jakarta.persistence.OptimisticLockException; |
| 7 | +import jakarta.persistence.Version; |
| 8 | +import org.hibernate.StaleObjectStateException; |
| 9 | +import org.hibernate.testing.orm.junit.DomainModel; |
| 10 | +import org.hibernate.testing.orm.junit.JiraKey; |
| 11 | +import org.hibernate.testing.orm.junit.SessionFactory; |
| 12 | +import org.hibernate.testing.orm.junit.SessionFactoryScope; |
| 13 | +import org.junit.jupiter.api.Test; |
| 14 | + |
| 15 | +import static org.junit.jupiter.api.Assertions.assertFalse; |
| 16 | +import static org.junit.jupiter.api.Assertions.assertNotNull; |
| 17 | +import static org.junit.jupiter.api.Assertions.assertNull; |
| 18 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 19 | +import static org.junit.jupiter.api.Assertions.fail; |
| 20 | + |
| 21 | +@SessionFactory |
| 22 | +@DomainModel(annotatedClasses = DeleteDetachedTest.Thing.class) |
| 23 | +@JiraKey("HHH-18553") |
| 24 | +public class DeleteDetachedTest { |
| 25 | + @Test void testCanRemove(SessionFactoryScope scope) { |
| 26 | + Thing thing = new Thing(); |
| 27 | + thing.stuff = "Some stuff about the thing"; |
| 28 | + scope.inTransaction(s -> s.persist(thing)); |
| 29 | + scope.inTransaction(s -> { |
| 30 | + Thing otherThing = s.find(Thing.class, thing.id); |
| 31 | + assertNotNull(otherThing); |
| 32 | + s.remove(thing); |
| 33 | + assertFalse(s.contains(thing)); |
| 34 | + assertFalse(s.contains(otherThing)); |
| 35 | + }); |
| 36 | + scope.inTransaction(s -> assertNull(s.find(Thing.class, thing.id))); |
| 37 | + } |
| 38 | + @Test void testCantRemove(SessionFactoryScope scope) { |
| 39 | + Thing thing = new Thing(); |
| 40 | + thing.stuff = "Some stuff about the thing"; |
| 41 | + scope.inTransaction(s -> s.persist(thing)); |
| 42 | + scope.inTransaction(s -> { |
| 43 | + Thing otherThing = s.find(Thing.class, thing.id); |
| 44 | + otherThing.stuff = "Other different stuff about the thing"; |
| 45 | + assertNotNull(otherThing); |
| 46 | + try { |
| 47 | + s.remove(thing); |
| 48 | + fail("Should have failed because detached object is stale"); |
| 49 | + } |
| 50 | + catch (OptimisticLockException exception) { |
| 51 | + // expected |
| 52 | + assertTrue( exception.getCause() instanceof StaleObjectStateException ); |
| 53 | + } |
| 54 | + assertFalse(s.contains(thing)); |
| 55 | + assertTrue(s.contains(otherThing)); |
| 56 | + }); |
| 57 | + scope.inTransaction(s -> assertNotNull(s.find(Thing.class, thing.id))); |
| 58 | + } |
| 59 | + @Entity |
| 60 | + static class Thing { |
| 61 | + @GeneratedValue @Id long id; |
| 62 | + @Version int version; |
| 63 | + String stuff; |
| 64 | + } |
| 65 | +} |
0 commit comments