MapStruct Getting Started Use Cases
The following are commonly used examples. You can change them according to your needs.
@Data
public class UserDO{
private int age;
private String name;
private Role role;
private String date;
}
@Data
public class UserDTO{
private int dtoAge;
private String dtoName;
private Guest guest;
private Date date;
}
import .*;
import ;
@Mapper
public interface UserConvert{
UserConvert INSTANCE = ();
//Method 1 Return value method
UserDO DTOConvertDO(UserDTO dto);
//Method 2: Add annotations to parameters
void DTOConvertDO(UserDTO dto,@MappingTarget UserDO user)
//Automatically ignore the empty value of the source object
@BeanMapping(nullValuePropertyMappingStrategy = )
UserDO DTOConvertDO(UserDTO dto);
//resultType specifies the return target type, ignoreByDefault = true: ignore all unmapped attributes in the target type CarDto.
//mappingControl =: If there are unmatched properties, filter them without reporting errors or warnings
@BeanMapping(resultType = ,ignoreByDefault = true, mappingControl = ) UserDO DTOConvertDO(UserDTO dto);
//Mapping between attributes with the same name, the dtoName of the specified dto is mapped to the name in Do
@Mapping(source = "dtoName",target = "name")
//Conditional mapping, mapping and assignment if you are older than 18 years old
@Mapping(condition = "java(() >= 18)", target = "age")
//Ignore the specified value mapping
@Mapping(source="guest",ignore=true)
void DTOConvertDO(UserDTO dto,@MappingTarget UserDO user)
//Mapping between properties with the same name, including the assignment of the second-level object properties below it. dateFotmat specifies the time format
@Mappings({
@Mapping(source = "dtoName",target = "name"),
@Mapping(source = "dtoAge",target = "age")
@Mapping(source = "",target = "")
@Mapping(source = "date",target = "date",dateFotmat="yyyy-MM-dd")
})
void DTOConvertDO(UserDTO dto,@MappingTarget UserDO user)
// When it is null, no value is assigned, you can set it one by one.
@Mapping(target = "dtoName", source = "name", defaultExpression = "java(null)")
void DTOConvertDO(UserDTO dto,@MappingTarget UserDO user)
//Collection mapping
@MapMapping(valueDateFormat="yyyy-MM-dd")
void DTOConvertDO(Map<String,Date> dto,@MappingTarget Map<String,String> map)
}
Note:
@BeanMapping(nullValuePropertyMappingStrategy = ): Ignore mapping assignments to null values
@Mappingtarget: Specify the assignment target object, where is the assignment.
@Mapping(source = "dtoName", target = "name"): Specify the mapping relationship, assign attributes with different names, assign the dtoName under UserDTO to the name under UserDO
@Mappings({
@Mapping(source = "dtoName",target = "name"),
@Mapping(source = "dtoAge",target = "age")
}): Specify the mapping relationship, multiple times.