Search in sources :

Example 1 with DataChangedException

use of org.jooq.exception.DataChangedException in project jOOQ by jOOQ.

the class UpdatableRecordImpl method checkIfChanged.

/**
 * Perform an additional SELECT .. FOR UPDATE to check if the underlying
 * database record has been changed compared to this record.
 */
private final void checkIfChanged(TableField<R, ?>[] keys) {
    SelectQuery<R> select = create().selectQuery(getTable());
    Tools.addConditions(select, this, keys);
    // can emulate it, though!
    if (!NO_SUPPORT_FOR_UPDATE.contains(create().dialect()))
        select.setForUpdate(true);
    R record = select.fetchOne();
    if (record == null)
        throw new DataChangedException("Database record no longer exists");
    for (Field<?> field : fields.fields.fields) {
        Object thisObject = original(field);
        Object thatObject = record.original(field);
        if (!StringUtils.equals(thisObject, thatObject))
            throw new DataChangedException("Database record has been changed");
    }
}
Also used : DataChangedException(org.jooq.exception.DataChangedException)

Example 2 with DataChangedException

use of org.jooq.exception.DataChangedException in project jOOQ by jOOQ.

the class Example_2_2_OptimisticLocking method run.

@Test
public void run() throws SQLException {
    Connection connection = connection();
    DSLContext dsl = DSL.using(connection, new Settings().withExecuteWithOptimisticLocking(true));
    try {
        Tools.title("Applying optimistic locking");
        BookRecord book1 = dsl.selectFrom(BOOK).where(BOOK.ID.eq(1)).fetchOne();
        BookRecord book2 = dsl.selectFrom(BOOK).where(BOOK.ID.eq(1)).fetchOne();
        book1.setTitle("New Title");
        book1.store();
        book2.setTitle("Another Title");
        book2.store();
    } catch (DataChangedException expected) {
        expected.printStackTrace();
    } finally // Don't store the changes
    {
        connection.rollback();
    }
}
Also used : DataChangedException(org.jooq.exception.DataChangedException) Connection(java.sql.Connection) DSLContext(org.jooq.DSLContext) BookRecord(org.jooq.example.db.h2.tables.records.BookRecord) Settings(org.jooq.conf.Settings) Test(org.junit.Test)

Aggregations

DataChangedException (org.jooq.exception.DataChangedException)2 Connection (java.sql.Connection)1 DSLContext (org.jooq.DSLContext)1 Settings (org.jooq.conf.Settings)1 BookRecord (org.jooq.example.db.h2.tables.records.BookRecord)1 Test (org.junit.Test)1