java - jOOQ transaction does not work as expected - Stack Overflow

时间: 2025-01-06 admin 业界

I have a back-end API that does a simple 'getOrCreate' operation on DB.

For some reason, this API can get called twice at the same time, hence I have made a change to not create the record twice (by adding a transaction). However, every single time that the code runs, two records are created.

Two API calls share the same DSLContext instance, but each call runs on a separate thread.

Sample code:

public static Record getOrCreateData(int id, DSLContext dslContext) {

        var result = dslContext.transactionResult(config -> {
            var dsl = DSL.using(config);
            var existingData = dsl
                .selectFrom(TABLE1)
                .where(TABLE1.LINK_ID.eq(id))
                .fetchOptionalInto(RecordDto.class);

            if ( existingData.isPresent() ) {
                return existingData.get();
            }

            var record = dsl.newRecord(TABLE1);
...
            record.store();

            return record.into(RecordDto.class);
        });

        return result;
    }

I'm using Hikari CP with Postgresql database with default config.

How can I fix this?