1. 程式人生 > >開發利器mapstruct

開發利器mapstruct

print 較差 互轉 use 大量 private hda word pst

背景:

在業務代碼中,會出現很多dto之間的相互轉換,就是兩個dto屬性的各種get,set,會造成大量的冗余代碼,所以出現了一些工具,比如Spring中的beanUtil,但是beanutil是運行時處理的,性能較差,所以出現了一款利器,mapstruct,它是編譯生效的,類似lombok,所以性能大大提升

maven導入:

         <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>1.2
.0.Final</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.2.0.Final</version> </dependency>

建立兩個類,一個UserEntity,一個UserDTO

@Data
public class UserEntity {
    private String name;
    private String password;
    private Integer age;
    private Date birthday;
    private String sex;
}
@Data
public class UserVO {
    private String name;
    private String age;
    private String birthday;
    private String gender;
}

接下來是關鍵的映射,UserMapper接口

@Mapper
public interface UserMapper {

    UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);

    /**
     * 1、entity與vo中屬性名相同時候默認映射,(比如name),屬性名相同屬性類型不同也會映射,(比如birthday,一個Data,一個String)
     * 2、entity與vo中屬性名不同的,需要通過@Mapping明確關系來形成映射(如sex對應gender)
     * 3、無映射關系屬性被忽略(如UserEntity的password)
     */
    @Mappings({
            @Mapping(target = "gender", source = "sex"),    
    })
    UserVO entityToVO(UserEntity entity);

}

測試代碼

public class UserTest {

    public static void main(String[] args)  {
        UserEntity userEntity = new UserEntity();
        userEntity.setAge(1);
        userEntity.setName("snow");
        userEntity.setPassword("123");
        userEntity.setSex("");
        userEntity.setBirthday(new Date());

        UserVO userVO = UserMapper.INSTANCE.entityToVO(userEntity);
        System.out.println(userVO);
        System.out.println("=================");
        System.out.println(userEntity);

    }
}

結果如下:

UserVO(name=snow, age=1, birthday=18-5-11 下午9:23, gender=男)
=================
UserEntity(name=snow, password=123, age=1, birthday=Fri May 11 21:23:34 CST 2018, sex=男)

以上是簡單舉例,參考https://blog.csdn.net/OO570741825/article/details/78530022,在它基礎上做了些修正

開發利器mapstruct