|
| 1 | +package org.hibernate.orm.test.mapping.mappedBy; |
| 2 | + |
| 3 | +import jakarta.persistence.Column; |
| 4 | +import jakarta.persistence.Entity; |
| 5 | +import jakarta.persistence.Id; |
| 6 | +import jakarta.persistence.OneToMany; |
| 7 | +import org.hibernate.Hibernate; |
| 8 | +import org.hibernate.testing.orm.junit.DomainModel; |
| 9 | +import org.hibernate.testing.orm.junit.SessionFactory; |
| 10 | +import org.hibernate.testing.orm.junit.SessionFactoryScope; |
| 11 | +import org.junit.jupiter.api.Test; |
| 12 | + |
| 13 | +import java.util.ArrayList; |
| 14 | +import java.util.List; |
| 15 | + |
| 16 | +import static jakarta.persistence.CascadeType.PERSIST; |
| 17 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 18 | + |
| 19 | +@SessionFactory |
| 20 | +@DomainModel(annotatedClasses = {MappedByNonAssociationTest.Loan.class, MappedByNonAssociationTest.Extensions.class}) |
| 21 | +public class MappedByNonAssociationTest { |
| 22 | + |
| 23 | + @Test void test(SessionFactoryScope scope) { |
| 24 | + Extensions ex = new Extensions(); |
| 25 | + ex.exExtensionDays = 3L; |
| 26 | + ex.exNo = 2L; |
| 27 | + ex.exLoanId = 4L; |
| 28 | + |
| 29 | + Loan loan = new Loan(); |
| 30 | + loan.id = 4L; |
| 31 | + loan.extensions.add(ex); |
| 32 | + |
| 33 | + scope.inTransaction(s -> s.persist(loan)); |
| 34 | + Loan l1 = scope.fromTransaction(s -> { |
| 35 | + Loan ll = s.get(Loan.class, loan.id); |
| 36 | + Hibernate.initialize(ll.extensions); |
| 37 | + return ll; |
| 38 | + }); |
| 39 | + assertEquals( 1, l1.extensions.size() ); |
| 40 | + assertEquals( loan.id, l1.id ); |
| 41 | + assertEquals( ex.exLoanId, l1.extensions.get(0).exLoanId ); |
| 42 | + Loan l2 = scope.fromSession(s -> s.createQuery("from Loan join fetch extensions", Loan.class).getSingleResult()); |
| 43 | + assertEquals( 1, l2.extensions.size() ); |
| 44 | + assertEquals( loan.id, l2.id ); |
| 45 | + assertEquals( ex.exLoanId, l2.extensions.get(0).exLoanId ); |
| 46 | + } |
| 47 | + |
| 48 | + @Entity(name="Loan") |
| 49 | + static class Loan { |
| 50 | + @Id |
| 51 | + @Column(name = "LOAN_ID") |
| 52 | + private Long id; |
| 53 | + |
| 54 | + @OneToMany(cascade = PERSIST, mappedBy = "exLoanId") |
| 55 | + private List<Extensions> extensions = new ArrayList<>(); |
| 56 | + } |
| 57 | + |
| 58 | + @Entity(name="Extensions") |
| 59 | + static class Extensions { |
| 60 | + @Id |
| 61 | + @Column(name = "EX_LOAN_ID") |
| 62 | + private Long exLoanId; |
| 63 | + @Id |
| 64 | + @Column(name = "EX_NO") |
| 65 | + private Long exNo; |
| 66 | + @Column(name = "EX_EXTENSION_DAYS") |
| 67 | + private Long exExtensionDays; |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments