Search code examples
spring-data-jpacomposite-keydata-jpa-test

Problem when testing via @DataJpaTest with composite key entities


I'm trying to test an entity that I've mapped with a composite key.

Simply, I tried to test from the Repository layer, but the desired data and results did not come out.

I don't use @CreationTimestamp very often, so you don't have to mention this part, but if this part is a problem,

please mention it.

Please take into account typos. Thanks.

The code looks like this:

@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode
@Getter
@IdClass(TestId.class)
@ToString
public class TestEntity  {

    @Id
    private Long groupCode;

    @Id
    private Long code;

    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private LocalDateTime regDate;

    @UpdateTimestamp
    @Column(insertable = false)
    private LocalDateTime modDate;

    public TestEntity(Long groupCode, Long code) {
        this.groupCode = groupCode;
        this.code = code;
    }
}

Repository

public interface TestEnttiyRepository extends JpaRepository<TestEntity, TestId> {
}

Composite-id Class

@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode
public class TestId implements Serializable {

    private Long groupCode;
    private Long code;

    public TestId(Long groupCode, Long code) {
        this.groupCode = groupCode;
        this.code = code;
    }
}
@DataJpaTest
class TestEnttiyRepositoryTest {

    @Autowired
    private TestEnttiyRepository testEnttiyRepository;

    @Commit
    @Test
    void test() {
        TestEntity testEntity = new TestEntity(1L, 1L);

        TestEntity save = testEnttiyRepository.save(testEntity);
        System.out.println("save = " + save);
    }

}

Test Result

Hibernate: 
    select
        testentity0_.code as code1_5_0_,
        testentity0_.group_code as group_co2_5_0_,
        testentity0_.mod_date as mod_date3_5_0_,
        testentity0_.reg_date as reg_date4_5_0_ 
    from
        test_entity testentity0_ 
    where
        testentity0_.code=? 
        and testentity0_.group_code=?
save = TestEntity(groupCode=1, code=1, regDate=null, modDate=null)
Hibernate: 
    insert 
    into
        test_entity
        (reg_date, code, group_code) 
    values
        (?, ?, ?)

Currently my question here is this.

  1. The order of the output value through System.out.println and the insert query through save is reversed.
  2. The LocalDateTime was not added automatically.

Solution

  • The order of the output value through System.out.println and the insert query through save is reversed.

    Repository.save just as EntityManager.persist don't save anything. They just make entities managed which will result in them being saved when a flush happens, which is at the end of the transaction, which in turn is at the end of your method, so after the System.out statement.