Data transfer object (DTO) is an object that carries data between processes. Working with a remote interface where each call to it is expensive. Response to each call should bring as much data as possible so if multiple request are required to bring data for a particular task, data to be brought can be combined in a DTO so only one request can bring all the data required.

Manually creating and maintaining DTO object for your domain classes is labor intensive and error-prone. Grails makes it easy as we have DTO plug-in for Grails.

generate DTO
grails generate-dto [--all] [--non-recursive] [domain class ...]

The above command will generate DTO class for specified Domain class in the src/java directory.

There are two optional arguments:

  • –all : The argument will generate DTOs for all your domain classes.
  • –non-recursive : The argument will not generate DTOs for domain class relations/associations.

For example, if you have a domain class

package com.example

class Student {

    String name
    int rollNo

}

the command will create a file src/java/com/example/StudentDTO.java that looks like this:

package com.example

public class StudentDTO implements grails.plugins.dto.DTO {

    private static final long serialVersionUID = 1L;

    private String name;
    private int rollNo;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getRollNo() {
        return rollNo;
    }

    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }
}

if you run above command without the optional parameters

grails generate-dto Post

Lets take another  example-
we have two domain classes

class Student {
    static hasMany = [books: Book];
    int rollNo;
}

class Book {
    String bookName
}

And running  the above command without any optional arguments will not only create a StudentDTO class that has the same persistent fields as Student, but it will also create DTO classes for all related classes, such as those declared via hasMany or belongsTo.

But if you want DTOs for your whole domain model then you can use the command below.

grails generate-dto --all

Converting domain instances to DTOs

Once you have a domain instance, you can create the corresponding DTOs by one of two methods:

domainClassObj as DTO
domainClassObj.toDTO()

Both methods will return root DTO instance.

These methods work well if the DTO classes have the same package as their corresponding domain classes, but if you have used package substitution during the DTO generation. In such cases, you can use a variation of the second method:

import ....BookDTO
…
def dto = student.toDTO(StudentDTO)

That’s all.
Thank you so much all 🙂