'Inconsistency between postgres and hibernate

Inconsistency between hibernate and postres. Consider we have table student having 2 columns id(Primary Key) and name. Perform the following concurrent query on table

POSTGRES:

1. BEGIN;                                                 BEGIN;
2. SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;          SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
3. SELECT * FROM STUDENTS WHERE ID = 2;                   SELECT * FROM STUDENTS WHERE ID = 1;
4. INSERT INTO STUDENTS(ID, NAME) VALUES(2, 'TOM');       INSERT INTO STUDENTS(ID, NAME) VALUES(1, 'HANK');                               
5. COMMIT;                                                COMMIT;

Started 2 sessions of postres Perform line 1 - 4 on the right in and then in 2nd session run line 1-4 on the left and then commit both the transactions and both of them commits successfully.

HIBERNATE:

@Transactional(isolation = Isolation.SERIALIZABLE, rollbackFor = [Exception::class])
    fun addStudent(id: Long, name: String) {
        val alreadyPresentStudent = studentsRepository.findByIdOrNull(id)
        if (alreadyPresentStudent != null) return
        val student = Student().apply {
            this.id = id;
            this.name = name
        }
        studentsRepository.save(student)
    }

Here when I call the above method with addStudent(1, "HANK") and before 1st transaction commits we call addStudent(2, "TOM"). The first gets flushed in the db, but I get following error for 2nd

"Could not execute because of read/write dependencies betweeen transactions"


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source