DTO Generator
DTO (data transfer object) is an object that carries data between processes. DTOs for JPA entities generally contain a subset of entity attributes. For example, if you need to expose only a few of the entity attributes via REST API, you can map entities to DTOs with those attributes and serialize only them. Basically, DTOs allow you to decouple presentation/business logic layer from the data access layer.
JPA Buddy offers DTO generation from JPA entities via visual designer:
When creating DTOs, JPA Buddy provides the flexibility to choose from the following options:
Java record – Generates a DTO as a Java record, providing a concise and immutable representation of the DTO with automatic implementations of
equals()
,hashCode()
, andtoString()
.All args constructor – Generates a constructor that accepts arguments for all fields of the DTO.
equals() and hashCode() – Generates the
equals()
andhashCode()
methods for the DTO based on its fields.toString() – Generates the
toString()
method for the DTO, providing a string representation of its fields.Mutable – By default, the generated DTOs are immutable with final fields and no setters. If you need mutable DTOs with private fields and setters, you can check this option.
Fluent setters – This option is available when selecting the Mutable option. It allows the generated setters to return
this
instead ofvoid
, enabling method chaining for multiple setter calls.Ignore unknown properties for json – Applies the
@JsonIgnoreProperties(ignoreUnknown = true)
annotation to the DTO, allowing it to ignore any unknown properties during JSON deserialization. Only available when the Jackson Annotations dependency is included in the project.
![new-dto-options.png new-dto-options.png](https://resources.jetbrains.com/help/img/idea/2024.3/new-dto-options.png)
JPA Buddy simplifies the generation of DTOs by providing Lombok support in the most optimal way.
For example, when you choose the All args constructor
, equals() and hashCode()
and toString()
options in the DTO generator wizard, JPA Buddy applies @Value
to the generated DTO, discarding the redundant access modifiers to keep your code clean.
![new-dto-lombok-value new-dto-lombok-value](https://resources.jetbrains.com/help/img/idea/2024.3/new-dto-lombok-value.png)
@Value
public class OwnerDto implements Serializable {
String firstName;
String lastName;
String telephone;
}
In case you need a mutable DTO with the same parameters as in the example above, JPA Buddy will add @Data
, @AllArgsConstructor
and @NoArgsConstructor
annotations instead.
![new-dto-lombok-data new-dto-lombok-data](https://resources.jetbrains.com/help/img/idea/2024.3/new-dto-lombok-data.png)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OwnerDto implements Serializable {
private String firstName;
private String lastName;
private String telephone;
}
tip
To use this feature, make sure to add Lombok dependencies to your project and enable it in the DTO Declaration Settings.
Entities can reference other entities via associations, and JPA Buddy allows you to generate DTOs for the referenced entities from the same window. Just check the referenced entity in the tree, choose the DTO type and pick the required fields.
![inner-dtos.png inner-dtos.png](https://resources.jetbrains.com/help/img/idea/2024.3/inner-dtos.png)
Let’s look at the available DTO types:
New Class – a new class will be created in a separate file.
New Nested Class – a new public static nested class will be created.
Existing Class – you can select a DTO class that already exists in the project.
Flat – all inner class fields will be top-class fields. The names of the generated entities will be formed by combining the inner class name with the field names.
If you use SDK version 16 and higher in your project, then JPA Buddy will provide an additional Java Record checkbox in the New DTO wizard. To check the SDK version of the project, open File | Project Structure.
![project-structure project-structure](https://resources.jetbrains.com/help/img/idea/2024.3/project-structure.png)
JPA Buddy provides an Entity from POJO action that helps to generate a JPA entity from any java/kotlin class. This feature may be helpful if you develop your application following the API-first approach: define DTOs for the API first and implement the data model later.
JPA Buddy's notable feature is its ability to detect the relationship's cardinality and generate related entities or select existing ones:
![entity-from-pojo.png entity-from-pojo.png](https://resources.jetbrains.com/help/img/idea/2024.3/entity-from-pojo.png)
Nowadays, the DTO pattern is widely used in software development. It is not only used with JPA entities, but also with regular POJO classes. With JPA Buddy, you are not restricted to using DTOs with just JPA entities. You can create DTOs from any Java or Kotlin class, which gives you more flexibility and control over your code. For example, check out how easy you can use JPA Buddy with MongoDB documents:
MapStruct is a code generator that greatly simplifies the implementation of mappings. The Mapper class field appears in the New DTO window if your project contains the corresponding dependency. You can select an existing Mapper or create a new one.
note
This feature works with any domain entity (any Java/Kotlin classes), not only with JPA entities.
JPA Buddy analyzes MapStruct mappers and can define which DTO is associated with which entity. Thanks to this, you can see the DTOs in the corresponding section in the JPA Structure and navigate between entity and DTOs through gutter icons.
Also, JPA Buddy can help if you prefer to have a single big mapper interface with methods for all entities. In this case, use IntelliJ IDEA Generate Menu (AltInsert) in the open mapper class and create methods for any entity.
MapStruct allows declaring generic mappers:
public interface EntityMapper<D, E> {
E toEntity(D dto);
D toDto(E entity);
List<E> toEntity(List<D> dtoList);
List<D> toDto(List<E> entityList);
}
Such a mapper is convenient to use as a parent for all other mappers and keep them concise and clean:
@Mapper(componentModel = "spring")
public interface UserMapper extends EntityMapper<UserDTO, User> {}
Still, complex mapping logic can be easily added if required:
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring")
public interface ProjectMapper extends EntityMapper<ProjectDTO, Project> {
@AfterMapping
default void linkTasks(@MappingTarget Project project) {
project.getTasks().forEach(task -> task.setProject(project));
}
}
JPA Buddy supports generic mappers' inheritance:
JPA Buddy provides flexible settings for mapper declaration. To configure naming patterns or mapping naming strategy for collections, open Tools | JPA Buddy | Mapper Declaration:
![mapper-declaration mapper-declaration](https://resources.jetbrains.com/help/img/idea/2024.3/mapper-declaration.png)
ModelMapper is one of the most popular libraries for converting entities to DTOs and vice versa. JPA Buddy provides many features that streamline the mapping process even further, including:
Generating custom mapping methods.
Providing code scaffolding for mapping a single entity or a collection of entities to DTOs and vice versa, with the help of postfix autocompletion.
Enabling on-the-fly injection of the ModelMapper bean into the relevant class.
note
JPA Buddy assumes that you have declared the ModelMapper bean in your project.
Blaze-Persistence is a strong persistence framework for Java applications. It offers advanced querying and optimization techniques to simplify data access development and improve developer productivity. JPA Buddy supports this framework to create Entity Views for JPA entities, whenever the relevant library is included in the project.
You can create an Entity View through the following steps:
JPA Structure | Plus button | Blaze Persistence Entity View
JPA Designer | Plus button | Blaze Persistence Entity View
Editor Toolbar | DTOs and Spring Data Projections | Create Blaze Persistence Entity View
Project | New | Other | Blaze Persistence Entity View
After that, a dialog for creating an Entity View will open. Besides the standard options for configuration, such as package name or source root, you can configure:
Parent Entity View
JPA Entity for which the Entity View will be created
Entity View class name
Also, you can set the Entity View to creatable or updatable through the respective checkboxes.
![blaze-persistence-entity-view.png blaze-persistence-entity-view.png](https://resources.jetbrains.com/help/img/idea/2024.3/blaze-persistence-entity-view.png)
Similar to other types of DTOs, JPA Buddy provides the ability to configure an inner Entity Views for associations.
Therefore, the configuration above will generate the following Entity View:
@EntityView(Person.class)
@UpdatableEntityView
@CreatableEntityView
public interface PersonView extends BaseView {
@IdMapping
Long getId();
void setId(Long id);
String getName();
void setName(String name);
int getAge();
void setAge(int age);
@Mapping("posts.id")
Set<Long> getPostIds();
void setPostIds(Set<Long> postIds);
}
The selected checkboxes generated the @UpdatableEntityView
and @CreatableEntityView
annotations. It's important to note that updatable or creatable entity views require an attribute marked with the @IdMapping annotation. Therefore, once you tick one of the checkboxes, JPA Buddy will automatically select the attribute marked in the entity with an @Id
annotation. Also, updatable or creatable entity views will have setters for all attributes.
DTOs are commonly used at the API controller level to define only the fields required by the client. That's why DTOs nearly copy the structure of their entities. There are popular frameworks to map entities to DTOs and vice versa: MapStruct and ModelMapper. They auto-map namesake properties. However, changing the property name in an entity often leads to a corrupted mapping logic. JPA Buddy helps developers refactor entity properties along with their related fields in DTOs:
If you happen to add a new attribute to an entity, the corresponding DTOs may also need to be updated with this new field. JPA Buddy enables you to add a new field to all the required DTOs at once. Moreover, if you prefer typing the code manually instead of using wizards, JPA Buddy can help you with that too! Just start typing the name of the field that is not in your DTO, and it will be correctly added to the class. The best part is that it even works with associations!
note
This feature works with any domain entity (any Java/Kotlin classes), not only with JPA entities.
![dto-declarations-preferences dto-declarations-preferences](https://resources.jetbrains.com/help/img/idea/2024.3/dto-declarations-preferences.png)
Each project may follow its own conventions for code writing. In the Tools | JPA Buddy | DTO Declaration you can configure:
Serializable type.
Class name postfix.
Whether to use Lombok or not.
Comment link regexp (The feature is disabled when the field is empty). It allows JPA Buddy to associate a DTO with its JPA Entity. To specify a placeholder for the target entity FQN (Fully Qualified Name) in a comment use the
(?<entity>.*)
pattern. So, if the regexp is defined asDTO for (?:the )?\{@link (?<entity>.*)\}
it will be resolved in the following comment://DTO for the {@link io.jpabuddy.demo.entities.Project} entity
Class name regexp. This option is useful if you follow an obligatory naming convention for DTOs. It allows JPA Buddy to associate a DTO with its JPA Entity using a DTO name only. You can specify a placeholder for the simple class name of the target JPA entity using the
(?<entity>.)
pattern. E.g.,(?.)Dto
means that theMyEntityDto
class will be considered as a DTO forMyEntity
. This feature is disabled when the field is empty.Class comment. Defines the comment that will be generated over the DTO class.
JPA Buddy offers seamless configuration of bean validation constraints for DTO fields within its dedicated DTO generation wizard. In addition to defining validations from scratch, you can automatically transfer the validations from the corresponding entities and manage them in the same wizard.
![dto-validation-rules dto-validation-rules](https://resources.jetbrains.com/help/img/idea/2024.3/dto-validation-rules.png)
With the flexibility to enable or disable each constraint and customize validation messages, this comprehensive feature allows you to conveniently manage a full range of bean validation constraints for your DTO fields, ensuring consistency and reusability across your application.
tip
To enable the validation list, it is necessary to include either the Hibernate Validator or Spring Boot Starter Validation dependency.
Once JPA Buddy associates a DTO class with its corresponding entity:
The DTO class will appear in the Dto & Projections section in the JPA Structure tab and in the Editor Toolbar (1)
A gutter icon will appear in the DTO class, providing a convenient way to navigate to its associated entity (2)
![dto-navigation dto-navigation](https://resources.jetbrains.com/help/img/idea/2024.3/dto-navigation.png)
Thanks for your feedback!