#实用#mapStruct的使用

查看 mapStruct 生成的demo
#实用#mapStruct的使用_第1张图片

    <!-- mapStruct 对象转换 -->
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>1.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>1.2.0.Final</version>
        </dependency>


@Mapper
public interface UserConvert{
    @Mappings({
            @Mapping(target = "name",source = "username"),
            @Mapping(target = "password",source = "pwd"),
            @Mapping(target = "id",source = "id"),
            @Mapping(target = "dateStr",source = "date",dateFormat = "yyyy-MM-dd HH:mm:ss") ,
            @Mapping(target = "date",source = "dateStr",dateFormat = "yyyy-MM-dd")
    })
    Person fromPerson(UserInfo userInfo);
}
@Data
@Accessors(chain = true)
public class Person{
    private String name;
    private String password;
    private Long  id;
    private String dateStr;
    private Date   date;

}

@Data
@Accessors(chain = true)
public class UserInfo{
    private String username;
    private String pwd;
    private Integer id;
    private String dateStr;
    private Date date;
}

    @Test
    public void mapStructTest() {
        UserInfo userInfo = new UserInfo().setId(2).setPwd("666").setUsername("fjasfjlas");
        userInfo.setDate(new Date());//date -> str
        userInfo.setDateStr(Instant.now().toString());//str -> date
        Person person = userConvert.fromPerson(userInfo);
        System.out.println(person);
    }

    private UserConvert userConvert = Mappers.getMapper(UserConvert.class);

你可能感兴趣的:(CRUD)