首页 > 解决方案 > Constraint violation during maven clean install, but not when test ran independently

问题描述

I have the following issue:

The following constraint violation is reported during maven clean install, however when I run the test independently it is a succes, what can be the cause?

-------------------------------------------------------------------------------
Test set: com.gsm.GsmWeb.domain.repository.LyricsRepositoryTest
-------------------------------------------------------------------------------
Tests run: 3, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.35 s <<< FAILURE! - in com.gsm.GsmWeb.domain.repository.LyricsRepositoryTest
com.gsm.GsmWeb.domain.repository.LyricsRepositoryTest.testUpdateOfLyric  Time elapsed: 0.069 s  <<< ERROR!
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [idx_lyrics_song_nr_version]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at com.gsm.GsmWeb.domain.repository.LyricsRepositoryTest.testUpdateOfLyric(LyricsRepositoryTest.java:42)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at com.gsm.GsmWeb.domain.repository.LyricsRepositoryTest.testUpdateOfLyric(LyricsRepositoryTest.java:42)
Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '3-1' for key 'idx_lyrics_song_nr_version'
    at com.gsm.GsmWeb.domain.repository.LyricsRepositoryTest.testUpdateOfLyric(LyricsRepositoryTest.java:42)

and the code is:

@SpringBootTest(properties = { "initialize=false" })
@ActiveProfiles("devtest")
class LyricsRepositoryTest {

    @Autowired
    LyricsRepository lyricsRepository;

    @Autowired
    LyricsService lyricsService;

    @BeforeEach
    @AfterEach
    void setUp() {
        this.lyricsRepository.deleteAll();
    }

    @Test
    @Transactional
    void testUpdateOfLyric() {
        final Lyric lyric1 = createRandomLyric(3);
        this.lyricsRepository.save(lyric1);
        this.changeLyric(lyric1);

        final List<Lyric> lyric1f = this.lyricsRepository.findBySongNr(3);

        Assertions.assertEquals(1, lyric1f.size());
        Assertions.assertEquals(3, lyric1f.get(0).getSongNr());
        Assertions.assertEquals(7, lyric1f.get(0).getVersion());
        Assertions.assertEquals("EnText has been changed", lyric1f.get(0).getLyricEn());
    }

....

There is indeed a constraint but I shouldn't be violated as the database is emptied beforehand.

Regards,

Rick

标签: java

解决方案


I found it, @BeforeAll during build is in transactional and needs to be flushed.

Adding this resolved the problem:

        this.lyricsRepository.flush();


推荐阅读