|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: LGPL-2.1-or-later |
| 3 | + * Copyright Red Hat Inc. and Hibernate Authors |
| 4 | + */ |
| 5 | +package org.hibernate.orm.test.mapping.generated; |
| 6 | + |
| 7 | +import jakarta.persistence.Entity; |
| 8 | +import jakarta.persistence.Id; |
| 9 | +import org.hibernate.annotations.ColumnDefault; |
| 10 | +import org.hibernate.annotations.Generated; |
| 11 | +import org.hibernate.dialect.H2Dialect; |
| 12 | +import org.hibernate.testing.orm.junit.DomainModel; |
| 13 | +import org.hibernate.testing.orm.junit.Jira; |
| 14 | +import org.hibernate.testing.orm.junit.RequiresDialect; |
| 15 | +import org.hibernate.testing.orm.junit.SessionFactory; |
| 16 | +import org.hibernate.testing.orm.junit.SessionFactoryScope; |
| 17 | +import org.junit.jupiter.api.AfterAll; |
| 18 | +import org.junit.jupiter.api.Test; |
| 19 | + |
| 20 | +import static org.assertj.core.api.Assertions.assertThat; |
| 21 | + |
| 22 | +/** |
| 23 | + * @author Marco Belladelli |
| 24 | + */ |
| 25 | +@DomainModel(annotatedClasses = GeneratedWritableIdTest.TestEntity.class) |
| 26 | +@SessionFactory |
| 27 | +@Jira("https://hibernate.atlassian.net/browse/HHH-18679") |
| 28 | +@RequiresDialect(H2Dialect.class) |
| 29 | +public class GeneratedWritableIdTest { |
| 30 | + @Test |
| 31 | + public void testDefaultId(SessionFactoryScope scope) { |
| 32 | + scope.inTransaction( session -> { |
| 33 | + final TestEntity entity = new TestEntity( null, "entity_1" ); |
| 34 | + session.persist( entity ); |
| 35 | + session.flush(); |
| 36 | + assertThat( entity.getId() ).isEqualTo( 1L ); |
| 37 | + } ); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void testAssignedId(SessionFactoryScope scope) { |
| 42 | + scope.inTransaction( session -> { |
| 43 | + final TestEntity entity = new TestEntity( 2L, "entity_2" ); |
| 44 | + session.persist( entity ); |
| 45 | + session.flush(); |
| 46 | + assertThat( entity.getId() ).isEqualTo( 2L ); |
| 47 | + } ); |
| 48 | + } |
| 49 | + |
| 50 | + @AfterAll |
| 51 | + public void tearDown(SessionFactoryScope scope) { |
| 52 | + scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); |
| 53 | + } |
| 54 | + |
| 55 | + @Entity(name = "TestEntity") |
| 56 | + static class TestEntity { |
| 57 | + @Id |
| 58 | + @Generated(writable = true) |
| 59 | + @ColumnDefault("1") |
| 60 | + private Long id; |
| 61 | + |
| 62 | + private String name; |
| 63 | + |
| 64 | + public TestEntity() { |
| 65 | + } |
| 66 | + |
| 67 | + public TestEntity(Long id, String name) { |
| 68 | + this.id = id; |
| 69 | + this.name = name; |
| 70 | + } |
| 71 | + |
| 72 | + public Long getId() { |
| 73 | + return id; |
| 74 | + } |
| 75 | + |
| 76 | + public String getName() { |
| 77 | + return name; |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments