Just curious, is it possible to check if the field is available from the RecordContext by using ctx.recordType().field("modified_by")?

Alf Lervåg

1. juni 2024 kl. 20:55 skrev Dominik Hirt <[email protected]>:


If you're using jooq records, you could use a RecordListener like I do for a similar case.
My from field is modified_by and I populate it automatically:


/**
This RecordListener serves as an interceptor for the record.store() calls and inserts a ‘modified_by’ field if one exists. 
As it is not possible to search for the field, we search for the corresponding getter method ‘getModifiedBy’. 
As the search for a corresponding method is expensive, we remember the results in a cache.
 */
public class JooqRecordListenerSetModifiedBy extends DefaultRecordListener {

@Override
public void insertStart(RecordContext ctx) {
   setModifiedBy(ctx);
}

@Override
public void storeStart(RecordContext ctx) {
   setModifiedBy(ctx);
}

private void setModifiedBy(RecordContext ctx) {
   Record dbRecord = ctx.record();
   Class<?> clazz = dbRecord.getClass();
   Boolean hasModifiedBy = cache.get(clazz);

   if (hasModifiedBy == null) {
     hasModifiedBy = hasModifiedBy(dbRecord);
     cache.put(clazz, hasModifiedBy);
   }

   if (hasModifiedBy.equals(Boolean.TRUE)) {
     dbRecord.setValue(DSL.field(DSL.name("modified_by")), UsernameResolver.resolveUsername());
   }
}

private Boolean hasModifiedBy(Record dbRecord) {
   Boolean result = Boolean.FALSE;

   Method[] methods = dbRecord.getClass().getDeclaredMethods();
   for (Method method : methods) {
     if (method.getName().equals("getModifiedBy")) {
       result = Boolean.TRUE;
       break;
     }
   }
   return result;
}

}

The other audit field is modified_at and it's automatically set by JOOQ due to the maven plugin configuration:

<generator>
  <database>
    <recordTimestampFields>modified_at</recordTimestampFields>
        ....

Hope it helps
Dominik


--
You received this message because you are subscribed to the Google Groups "jOOQ User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
To view this discussion on the web visit https://groups.google.com/d/msgid/jooq-user/efd98b9e-c9b4-42c4-a013-9defe67256e9n%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "jOOQ User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
To view this discussion on the web visit https://groups.google.com/d/msgid/jooq-user/66D31107-2E5F-4642-B3DD-2BEF265ABC68%40lervag.net.

Reply via email to