danielc
danielc

Reputation: 539

Using jOOQ, how to get data type of a column by name

I am trying to get the data type of a field by name. I found the method getDataType which works great if I know the field (e.g. MY_TABLE.MY_COLUMN_NAME.getDataType()).

But I want to find it by field name (e.g. aDSL.fieldByName("my_column_name").getDataType()) where aDSL is of type DSLContext.

I want this because I am building a generic sort function on a collection used from the result set and I'd prefer to not rely on a developer to pass in the right data type for my comparator.

Any suggestions?

Upvotes: 1

Views: 2176

Answers (2)

Lukas Eder
Lukas Eder

Reputation: 221145

The types are available from Result or Record via:

Class<?> type1 = result.field("MY_COLUMN").getType()
Class<?> type2 = record.field("MY_COLUMN").getType()

See:

But most standard data types are Comparable anyway (I'm looking at the use-case in your answer), so why not just use Java 8's new Comparator.naturalOrder() and perhaps Comparator.reverseOrder()

Upvotes: 2

danielc
danielc

Reputation: 539

I was building a custom Comparator (I took my result set and converted it to a List, storing the Record - among other things - so that I could do all manner of manipulation on it, sorting, filtering, etc). In order to build the Comparator, I needed the type:

switch (R1.dataRecord.getValue( element ).getClass().toString())
{
   case "class java.lang.Long":
      compareResult = ( (Long) R1.dataRecord.getValue( element ) ).compareTo( (Long) R2.dataRecord.getValue( element ) );
      if (compareResult != 0)
           return compareResult * compareOrder;
           break;
   case "class java.lang.String":
      compareResult = ( (String) R1.dataRecord.getValue( element ) ).compareTo( (String) R2.dataRecord.getValue( element ) );
      if (compareResult != 0)
           return compareResult * compareOrder;
      break;
    ... etc ...
}

I was able to get the type from the record.

Upvotes: 1

Related Questions