教程 > mapstruct 教程 > 阅读:440

mapstruct 使用生成器——迹忆客-ag捕鱼王app官网

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

执行结果如下

mapstruct 使用生成器

查看笔记

扫码一下
查看教程更方便
网站地图