|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: Apache-2.0 |
| 3 | + * Copyright Red Hat Inc. and Hibernate Authors |
| 4 | + */ |
| 5 | +package org.hibernate.orm.test.where.annotations; |
| 6 | + |
| 7 | +import jakarta.persistence.Entity; |
| 8 | +import jakarta.persistence.FetchType; |
| 9 | +import jakarta.persistence.Id; |
| 10 | +import jakarta.persistence.JoinColumn; |
| 11 | +import jakarta.persistence.ManyToOne; |
| 12 | +import jakarta.persistence.Table; |
| 13 | +import org.hibernate.Hibernate; |
| 14 | +import org.hibernate.annotations.SQLRestriction; |
| 15 | +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; |
| 16 | +import org.hibernate.testing.orm.junit.JiraKey; |
| 17 | +import org.hibernate.testing.orm.junit.Jpa; |
| 18 | +import org.junit.jupiter.api.Test; |
| 19 | + |
| 20 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 21 | +import static org.junit.jupiter.api.Assertions.assertFalse; |
| 22 | +import static org.junit.jupiter.api.Assertions.assertNotNull; |
| 23 | + |
| 24 | +@Jpa(annotatedClasses = {ManyToOneLazyRestrictionTest.X.class, ManyToOneLazyRestrictionTest.Y.class}) |
| 25 | +class ManyToOneLazyRestrictionTest { |
| 26 | + @JiraKey("HHH-19565") |
| 27 | + @Test void test(EntityManagerFactoryScope scope) { |
| 28 | + scope.inTransaction(em -> { |
| 29 | + Y y = new Y(); |
| 30 | + X x = new X(); |
| 31 | + x.id = -1; |
| 32 | + y.x = x; |
| 33 | + em.persist(x); |
| 34 | + em.persist(y); |
| 35 | + }); |
| 36 | + // @SQLRestrictions should not be applied to |
| 37 | + // foreign key associations, or the FK will |
| 38 | + // be set to null when the entity is updated, |
| 39 | + // leading to data loss |
| 40 | + scope.inTransaction(em -> { |
| 41 | + Y y = em.find(Y.class, 0L); |
| 42 | + assertNotNull(y.x); |
| 43 | + assertFalse(Hibernate.isInitialized(y.x)); |
| 44 | + assertEquals(-1, y.x.getId()); |
| 45 | + y.name = "hello"; |
| 46 | + }); |
| 47 | + scope.inTransaction(em -> { |
| 48 | + Y y = em.find(Y.class, 0L); |
| 49 | + assertNotNull(y.x); |
| 50 | + assertEquals(-1, y.x.getId()); |
| 51 | + assertEquals("hello", y.name); |
| 52 | + assertFalse(Hibernate.isInitialized(y.x)); |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + @Entity |
| 57 | + @Table(name = "XX") |
| 58 | + @SQLRestriction("id>0") |
| 59 | + static class X { |
| 60 | + @Id |
| 61 | + long id; |
| 62 | + |
| 63 | + public long getId() { |
| 64 | + return id; |
| 65 | + } |
| 66 | + } |
| 67 | + @Entity |
| 68 | + @Table(name = "YY") |
| 69 | + static class Y { |
| 70 | + @Id |
| 71 | + long id; |
| 72 | + String name; |
| 73 | + @ManyToOne(fetch = FetchType.LAZY) |
| 74 | + @JoinColumn(name = "xx") |
| 75 | + X x; |
| 76 | + } |
| 77 | +} |
0 commit comments