Olav Grønås Gjerde

profile image
Full stack system architect with passion for Unix, Java, Python and databases.
Twitter @olavgg
1 year ago

Lighter select queries with Grails Criteria and DTO's

If you have a huge domain class like this:

class Sensor {

    Long id
    SensorType sensorType
    String parentTag
    String parentTagDescription
    EquipmentType equipmentType
    String runningSignalTimeserieName
    Boolean isPumpActive
    AssetProject assetProject
    SensorUnit unit
    Segment segment
    String segmentDescription
    String tag
    String description
    String deactivatedDescription
    String note
    String pAndID
    Float lValue
    Float llValue
    Float lllValue
    Float hValue
    Float hhValue
    Float hhhValue
    SensorStatus status
    Boolean deactivated = false
    LocalDateTime dateCreated
    LocalDateTime lastUpdated
    Person createdBy
    Person lastUpdatedBy
    SensorPumpGroup sensorPumpGroup
    String flowTimeserieName
    String flowTemperatureTimeserieName
    String flowPressureTimeserieName
    Double pipeArea
    Double flowDensity
    String flowDescription
    String velocityTimeserieName
    Long lastTimestampForVelocityTimeserie

}

You will always select all fields for your queries if you do not use do not use DTO's (Data Transfer Object). GORM has excellent support for DTO's with its data services. But its not mentioned in the documentation for how you can use DTO's with criterias.

Luckily it is really easy, first create a simple POJO/POGO

class SensorTag {
    long id
    String tag
}

Then write the criteria as this:

List<SensorTag> sensors = Sensor.withCriteria {
    resultTransformer(Transformers.aliasToBean(SensorTag))
    projections {
        property("id", "id")
        property("tag", "tag")
    }
    eq('deactivated', false)
} as List<SensorTag>