entity —》 VO
1、pom.xml 导入依赖
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.2.0.CR1</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.2.0.CR1</version>
<scope>provided</scope>
</dependency>
2、自定义接口
package com.southwind.mapper;
import com.southwind.entity.Category;
import com.southwind.entity.Product;
import com.southwind.vo.OrderVO;
import com.southwind.vo.ProductVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper
public interface ProductMapper {
ProductMapper mapper = Mappers.getMapper(ProductMapper.class);
@Mappings({
@Mapping(source = "productId",target = "id"),
@Mapping(source = "productName",target = "name"),
@Mapping(source = "productPrice",target = "price"),
@Mapping(source = "productStatus",target = "status",qualifiedByName = "convertStatus")
})
ProductVO pojo2vo(Product product);
@Named("convertStatus")
default Boolean convertStatus(Integer status){
if(status == 1)return true;
return false;
}
List<ProductVO> list2vo(List<Product> list);
@Mappings({
@Mapping(source = "product.productName",target = "product"),
@Mapping(source = "category.categoryName",target = "category")
})
OrderVO createOrder(Product product, Category category);
}
3、测试类
package com.southwind.mapper;
import com.southwind.entity.Category;
import com.southwind.entity.Product;
import com.southwind.vo.OrderVO;
import com.southwind.vo.ProductVO;
import org.junit.Test;
import org.springframework.beans.BeanUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class VOTest {
@Test
public void test() {
Product product = new Product(1,"电脑", new BigDecimal(6000),1);
ProductVO productVO = ProductMapper.mapper.pojo2vo(product);
System.out.println(productVO);
}
@Test
public void list(){
List<Product> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
list.add(new Product(i,"电脑"+i,new BigDecimal(6000),1));
}
List<ProductVO> productVOS = ProductMapper.mapper.list2vo(list);
for (ProductVO productVO : productVOS) {
System.out.println(productVO);
}
}
@Test
public void order(){
Product product = new Product(1, "电脑", new BigDecimal(6000),1);
Category category = new Category("电子产品");
OrderVO order = ProductMapper.mapper.createOrder(product, category);
System.out.println(order);
}
}