扫码一下
查看教程更方便
MapStruct 允许使用构建器。 我们可以使用构建器框架,也可以使用我们的自定义构建器。 在下面的示例中,我们使用的是自定义构建器。
打开映射直接字段章节中更新的项目映射。
使用以下代码更新 Student.java
Student.java
package com.jiyik.model; public class Student { private final String name; private final int id; protected Student(Student.Builder builder) { this.name = builder.name; this.id = builder.id; } public static Student.Builder builder() { return new Student.Builder(); } public static class Builder { private String name; private int id; public Builder name(String name) { this.name = name; return this; } public Builder id(int id) { this.id = id; return this; } public Student create() { return new Student( this ); } } public String getName() { return name; } public int getId() { return id; } }
使用以下代码更新 StudentMapper.java
StudentMapper.java
package com.jiyik.mapper; import com.jiyik.entity.StudentEntity; import com.jiyik.model.Student; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @Mapper public interface StudentMapper { Student getModelFromEntity(StudentEntity studentEntity); @Mapping(target="id", source="id") @Mapping(target="name", source="name") StudentEntity getEntityFromModel(Student student); }
使用以下代码更新 StudentMapperTest.java
StudentMapperTest.java
import com.jiyik.entity.StudentEntity; import com.jiyik.mapper.StudentMapper; import com.jiyik.model.Student; import org.junit.Test; import org.mapstruct.factory.Mappers; import static org.junit.Assert.assertEquals; public class StudentMapperTest { private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class); @Test public void testEntityToModel() { StudentEntity entity = new StudentEntity(); entity.setName("John"); entity.setId(1); Student model = studentMapper.getModelFromEntity(entity); assertEquals(entity.getName(), model.getName()); assertEquals(entity.getId(), model.getId()); } @Test public void testModelToEntity() { Student.Builder builder = Student.builder().id(1).name("John"); Student model = builder.create(); StudentEntity entity = studentMapper.getEntityFromModel(model); assertEquals(entity.getName(), model.getName()); assertEquals(entity.getId(), model.getId()); } }
运行以下命令来测试映射。
$ mvn clean test
执行结果如下