Spring Data Jpa Save and SaveAndFlush

springspring-dataspring-data-jpa

I'm using (Spring Data) JpaRepository to perform CURD operation. Here I saw two methods save and saveAndFlush. in both methods I got the same result, it successfully save data in the database. So what is the difference? I'm not using any sort of transactions mechanism, to issues commit command with the save method.

@Transactional
public BaseDto add(BulkPermitCategoryDto requestDto) {
    BaseDto baseDto = new BaseDto();
    try {
        BulkPermitCategory category = ObjectConverter
                .bulkPermitCategoryDtoToBulkPermitCategory(requestDto);
        bulkPermitCategoryRepository.saveAndFlush(category);
        baseDto.setStatusCode(0);

    } catch (Exception e) {
        log.error("exception occered ", e);
        e.printStackTrace();
    }

    return baseDto;
}

and

@Transactional
public BaseDto add(BulkPermitCategoryDto requestDto) {
    BaseDto baseDto = new BaseDto();
    try {
        BulkPermitCategory category = ObjectConverter
                .bulkPermitCategoryDtoToBulkPermitCategory(requestDto);
        bulkPermitCategoryRepository.save(category);
        baseDto.setStatusCode(0);

    } catch (Exception e) {
        log.error("exception occered ", e);
        e.printStackTrace();
    }

    return baseDto;
}

Best Answer

save()

save() is calling EntityManager.persist() or EntityManager.merge() this will not execute the SQL statements immediately. They will be executed on transaction commit.

saveAndFlush()

saveAndFlush() additionally calls EntityManager.flush() that will execute all retained SQL statements.

So if there are any constraint violations you will get the exceptions when calling saveAndFlush() but not when calling save()