1、添加依赖
2、三种场景(对象之间转换,list之间转换、多个对象转为一个对象)
一、依赖
org.mapstruct mapstruct-jdk81.2.0.Final org.mapstruct mapstruct-processor1.2.0.Final
二、三种场景
import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Mappings; import org.mapstruct.factory.Mappers; import java.util.List; @Mapper public interface UserAssemble { UserAssemble INSTANCE = Mappers.getMapper(UserAssemble.class); @Mappings({ @Mapping(source = "id", target = "id", defaultValue = "000000"), @Mapping(source = "username", target = "username") }) UserDTO entityToUserDTO(User user); ListentityListToUserDTOList(List user); @Mappings({ @Mapping(source = "user.id", target = "id"), @Mapping(source = "address.city", target = "address") }) UserDTO EntityAndAddressToUserDTO(User user, Address address); }
三、测试
import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { UserAssemble instance = UserAssemble.INSTANCE; User user = new User(); user.setId(111111L); user.setUsername("999999"); Listusers = new ArrayList<>(); users.add(user); Address address = new Address(); address.setCity("南京"); // 1、entity转换为dto UserDTO userDTO = instance.entityToUserDTO(user); System.out.println(userDTO.toString()); // 2、entityList转换为DTOList List userDTOS = instance.entityListToUserDTOList(users); System.out.println(userDTOS.toString()); // 3、多个对象转换到一个对象 UserDTO userDTO1 = instance.EntityAndAddressToUserDTO(user, address); System.out.println(userDTO1); } }
四、其它代码如下
public class User { private String username; private Long id; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
public class Address { private String province; private String city; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Address{" + "province='" + province + ''' + ", city='" + city + ''' + '}'; } }
public class UserDTO { private String username; private String id; private String address; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String other) { this.address = other; } @Override public String toString() { return "UserDTO{" + "username='" + username + ''' + ", id='" + id + ''' + ", other='" + address + ''' + '}'; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)