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:
equals()
, hashCode()
, and toString()
.equals()
and hashCode()
methods for the DTO based on its fields.toString()
method for the DTO, providing a string representation of its fields.this
instead of void
, enabling method chaining for multiple setter calls.@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.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.
@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.
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OwnerDto implements Serializable {
private String firstName;
private String lastName;
private String telephone;
}
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.
Let’s look at the available DTO types:
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...
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:
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.
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" (Cmd+N/Alt+Insert) in the open mapper class and create methods for any entity.
MapStruct allows to declare 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:
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:
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!
Each project may follow its own conventions for code writing. In the Tools -> JPA Buddy -> DTO Declaration you can configure:
(?<entity>.*)
pattern. So, if the regexp is defined as DTO for (?:the )?\{@link (?<entity>.*)\}
it will be resolved in the following comment://DTO for the {@link io.jpabuddy.demo.entities.Project} entity
(?<entity>.)
pattern. E.g., (?.)Dto
means that the MyEntityDto
class will be considered as a DTO for MyEntity
. This feature is disabled when the field is empty.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.
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.
To enable the validations 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: