Panduan Cepat untuk MapStruct

1. Ikhtisar

Pada artikel ini, kita akan menjelajahi penggunaan MapStruct yang, sederhananya, pembuat peta Java Bean.

API ini berisi fungsi yang secara otomatis memetakan antara dua Java Beans. Dengan MapStruct kita hanya perlu membuat antarmuka, dan perpustakaan secara otomatis akan membuat implementasi konkret selama waktu kompilasi.

2. MapStruct dan Pola Objek Transfer

Untuk sebagian besar aplikasi, Anda akan melihat banyak kode boilerplate yang mengubah POJO menjadi POJO lain.

Misalnya, jenis konversi umum terjadi antara entitas yang didukung persistensi dan DTO yang keluar ke sisi klien.

Jadi itulah masalah yang diselesaikan MapStruct - membuat pembuat peta kacang secara manual memakan waktu. Perpustakaan dapat menghasilkan kelas mapper kacang secara otomatis .

3. Maven

Mari tambahkan ketergantungan di bawah ini ke dalam pom.xml Maven kita :

 org.mapstruct mapstruct 1.3.1.Final 

Rilis stabil terbaru dari Mapstruct dan prosesornya keduanya tersedia dari Maven Central Repository.

Mari tambahkan juga bagian annotationProcessorPaths ke bagian konfigurasi plugin maven-compiler- plugin.

The mapstruct-prosesor yang digunakan untuk menghasilkan pelaksanaan mapper selama membangun:

 org.apache.maven.plugins maven-compiler-plugin 3.5.1  1.8 1.8   org.mapstruct mapstruct-processor 1.3.1.Final    

4. Pemetaan Dasar

4.1. Membuat POJO

Mari pertama-tama buat POJO Java sederhana:

public class SimpleSource { private String name; private String description; // getters and setters } public class SimpleDestination { private String name; private String description; // getters and setters }

4.2. Antarmuka Mapper

@Mapper public interface SimpleSourceDestinationMapper { SimpleDestination sourceToDestination(SimpleSource source); SimpleSource destinationToSource(SimpleDestination destination); }

Perhatikan bahwa kami tidak membuat kelas implementasi untuk SimpleSourceDestinationMapper kami - karena MapStruct membuatnya untuk kami.

4.3. Pembuat Peta Baru

Kita dapat memicu pemrosesan MapStruct dengan menjalankan instalasi mvn clean .

Ini akan menghasilkan kelas implementasi di bawah / target / generated-sources / annotations / .

Inilah kelas yang dibuat otomatis MapStruct untuk kita:

public class SimpleSourceDestinationMapperImpl implements SimpleSourceDestinationMapper { @Override public SimpleDestination sourceToDestination(SimpleSource source) { if ( source == null ) { return null; } SimpleDestination simpleDestination = new SimpleDestination(); simpleDestination.setName( source.getName() ); simpleDestination.setDescription( source.getDescription() ); return simpleDestination; } @Override public SimpleSource destinationToSource(SimpleDestination destination){ if ( destination == null ) { return null; } SimpleSource simpleSource = new SimpleSource(); simpleSource.setName( destination.getName() ); simpleSource.setDescription( destination.getDescription() ); return simpleSource; } }

4.4. Kasus Uji

Terakhir, dengan semua yang dihasilkan, mari kita tulis kasus pengujian yang akan menunjukkan bahwa nilai dalam SimpleSource cocok dengan nilai di SimpleDestination .

public class SimpleSourceDestinationMapperIntegrationTest { private SimpleSourceDestinationMapper mapper = Mappers.getMapper(SimpleSourceDestinationMapper.class); @Test public void givenSourceToDestination_whenMaps_thenCorrect() { SimpleSource simpleSource = new SimpleSource(); simpleSource.setName("SourceName"); simpleSource.setDescription("SourceDescription"); SimpleDestination destination = mapper.sourceToDestination(simpleSource); assertEquals(simpleSource.getName(), destination.getName()); assertEquals(simpleSource.getDescription(), destination.getDescription()); } @Test public void givenDestinationToSource_whenMaps_thenCorrect() { SimpleDestination destination = new SimpleDestination(); destination.setName("DestinationName"); destination.setDescription("DestinationDescription"); SimpleSource source = mapper.destinationToSource(destination); assertEquals(destination.getName(), source.getName()); assertEquals(destination.getDescription(), source.getDescription()); } }

5. Pemetaan Dengan Injeksi Ketergantungan

Selanjutnya, mari kita dapatkan instance mapper di MapStruct hanya dengan memanggil Mappers.getMapper (YourClass.class).

Tentu saja, itu adalah cara yang sangat manual untuk mendapatkan instans - alternatif yang jauh lebih baik adalah menyuntikkan mapper secara langsung di tempat yang kita butuhkan (jika proyek kita menggunakan solusi Injeksi Ketergantungan).

Untungnya MapStruct memiliki dukungan yang kuat untuk Spring dan CDI ( Contexts and Dependency Injection ).

Untuk menggunakan Spring IoC di mapper kita, kita perlu menambahkan atribut componentModel ke @Mapper dengan nilai spring dan untuk CDI adalah cdi .

5.1. Ubah Mapper

Tambahkan kode berikut ke SimpleSourceDestinationMapper :

@Mapper(componentModel = "spring") public interface SimpleSourceDestinationMapper

6. Memetakan Bidang Dengan Nama Bidang Berbeda

Dari contoh kami sebelumnya, MapStruct dapat memetakan kacang kami secara otomatis karena mereka memiliki nama bidang yang sama. Jadi bagaimana jika kacang yang akan kita petakan memiliki nama field yang berbeda?

Sebagai contoh, kami akan membuat kacang baru bernama Employee dan EmployeeDTO .

6.1. POJO baru

public class EmployeeDTO { private int employeeId; private String employeeName; // getters and setters }
public class Employee { private int id; private String name; // getters and setters }

6.2. Antarmuka Mapper

Saat memetakan nama bidang yang berbeda, kita perlu mengonfigurasi bidang sumbernya ke bidang targetnya dan untuk melakukannya kita perlu menambahkan anotasi @Mappings . Anotasi ini menerima larik anotasi @Mapping yang akan kita gunakan untuk menambahkan atribut target dan source.

Di MapStruct kita juga bisa menggunakan notasi titik untuk mendefinisikan anggota kacang:

@Mapper public interface EmployeeMapper { @Mappings({ @Mapping(target="employeeId", source="entity.id"), @Mapping(target="employeeName", source="entity.name") }) EmployeeDTO employeeToEmployeeDTO(Employee entity); @Mappings({ @Mapping(target="id", source="dto.employeeId"), @Mapping(target="name", source="dto.employeeName") }) Employee employeeDTOtoEmployee(EmployeeDTO dto); }

6.3. Kasus Uji

Sekali lagi kita perlu menguji apakah nilai objek sumber dan tujuan cocok:

@Test public void givenEmployeeDTOwithDiffNametoEmployee_whenMaps_thenCorrect() { EmployeeDTO dto = new EmployeeDTO(); dto.setEmployeeId(1); dto.setEmployeeName("John"); Employee entity = mapper.employeeDTOtoEmployee(dto); assertEquals(dto.getEmployeeId(), entity.getId()); assertEquals(dto.getEmployeeName(), entity.getName()); }

Kasus uji lainnya dapat ditemukan di proyek Github.

7. Memetakan Kacang Dengan Kacang Anak

Selanjutnya, kami akan menunjukkan cara memetakan kacang dengan referensi ke kacang lain.

7.1. Ubah POJO

Mari tambahkan referensi kacang baru ke objek Employee :

public class EmployeeDTO { private int employeeId; private String employeeName; private DivisionDTO division; // getters and setters omitted }
public class Employee { private int id; private String name; private Division division; // getters and setters omitted }
public class Division { private int id; private String name; // default constructor, getters and setters omitted }

7.2. Ubah Mapper

Here we need to add a method to convert the Division to DivisionDTO and vice versa; if MapStruct detects that the object type needs to be converted and the method to convert exists in the same class, then it will use it automatically.

Let’s add this to the mapper:

DivisionDTO divisionToDivisionDTO(Division entity); Division divisionDTOtoDivision(DivisionDTO dto);

7.3. Modify the Test Case

Let’s modify and add a few test cases to the existing one:

@Test public void givenEmpDTONestedMappingToEmp_whenMaps_thenCorrect() { EmployeeDTO dto = new EmployeeDTO(); dto.setDivision(new DivisionDTO(1, "Division1")); Employee entity = mapper.employeeDTOtoEmployee(dto); assertEquals(dto.getDivision().getId(), entity.getDivision().getId()); assertEquals(dto.getDivision().getName(), entity.getDivision().getName()); }

8. Mapping With Type Conversion

MapStruct also offers a couple of ready-made implicit type conversions, and for our example, we will try to convert a String date to an actual Date object.

For more details on implicit type conversion, you may read the MapStruct reference guide.

8.1. Modify the Beans

Add a start date for our employee:

public class Employee { // other fields private Date startDt; // getters and setters }
public class EmployeeDTO { // other fields private String employeeStartDt; // getters and setters }

8.2. Modify the Mapper

Modify the mapper and provide the dateFormat for our start date:

@Mappings({ @Mapping(target="employeeId", source = "entity.id"), @Mapping(target="employeeName", source = "entity.name"), @Mapping(target="employeeStartDt", source = "entity.startDt", dateFormat = "dd-MM-yyyy HH:mm:ss")}) EmployeeDTO employeeToEmployeeDTO(Employee entity); @Mappings({ @Mapping(target="id", source="dto.employeeId"), @Mapping(target="name", source="dto.employeeName"), @Mapping(target="startDt", source="dto.employeeStartDt", dateFormat="dd-MM-yyyy HH:mm:ss")}) Employee employeeDTOtoEmployee(EmployeeDTO dto);

8.3. Modify the Test Case

Let’s add a few more test case to verify the conversion is correct:

private static final String DATE_FORMAT = "dd-MM-yyyy HH:mm:ss"; @Test public void givenEmpStartDtMappingToEmpDTO_whenMaps_thenCorrect() throws ParseException { Employee entity = new Employee(); entity.setStartDt(new Date()); EmployeeDTO dto = mapper.employeeToEmployeeDTO(entity); SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString()); } @Test public void givenEmpDTOStartDtMappingToEmp_whenMaps_thenCorrect() throws ParseException { EmployeeDTO dto = new EmployeeDTO(); dto.setEmployeeStartDt("01-04-2016 01:00:00"); Employee entity = mapper.employeeDTOtoEmployee(dto); SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); assertEquals(format.parse(dto.getEmployeeStartDt()).toString(), entity.getStartDt().toString()); }

9. Mapping With an Abstract Class

Sometimes, we may want to customize our mapper in a way which exceeds @Mapping capabilities.

For example, in addition to type conversion, we may want to transform the values in some way as in our example below.

In such case, we can create an abstract class and implement methods we want to have customized and leave abstract those, that should be generated by MapStruct.

9.1. Basic Model

In this example, we'll use the following class:

public class Transaction { private Long id; private String uuid = UUID.randomUUID().toString(); private BigDecimal total; //standard getters }

and a matching DTO:

public class TransactionDTO { private String uuid; private Long totalInCents; // standard getters and setters }

The tricky part here is converting the BigDecimaltotalamount of dollars into a Long totalInCents.

9.2. Defining a Mapper

We can achieve this by creating our Mapper as an abstract class:

@Mapper abstract class TransactionMapper { public TransactionDTO toTransactionDTO(Transaction transaction) { TransactionDTO transactionDTO = new TransactionDTO(); transactionDTO.setUuid(transaction.getUuid()); transactionDTO.setTotalInCents(transaction.getTotal() .multiply(new BigDecimal("100")).longValue()); return transactionDTO; } public abstract List toTransactionDTO( Collection transactions); }

Here, we've implemented our fully customized mapping method for a single object conversion.

On the other hand, we left the method which is meant to map Collectionto a Listabstract, so MapStruct will implement it for us.

9.3. Generated Result

As we have already implemented the method to map single Transactioninto a TransactionDTO, we expect Mapstructto use it in the second method. The following will be generated:

@Generated class TransactionMapperImpl extends TransactionMapper { @Override public List toTransactionDTO(Collection transactions) { if ( transactions == null ) { return null; } List list = new ArrayList(); for ( Transaction transaction : transactions ) { list.add( toTransactionDTO( transaction ) ); } return list; } }

As we can see in line 12, MapStruct uses our implementation in the method, that it generated.

10. Before-mapping and After-mapping Annotations

Here's another way of customizing @Mapping capabilities by using @BeforeMapping and @AfterMapping annotations. The annotations are used to mark methods that are invoked right before and after the mapping logic.

They are quite useful in scenarios where we might want this behavior to be applied to all mapped super-types.

Let's take a look at an example that maps the sub-types of Car; ElectricCar, and BioDieselCar, to CarDTO.

While mapping we would like to map the notion of types to the FuelType enum field in the DTO, and after the mapping is done we'd like to change the name of the DTO to uppercase.

10.1. Basic Model

In this example, we’ll use the following classes:

public class Car { private int id; private String name; }

Sub-types of Car:

public class BioDieselCar extends Car { }
public class ElectricCar extends Car { }

The CarDTO with an enum field type FuelType:

public class CarDTO { private int id; private String name; private FuelType fuelType; }
public enum FuelType { ELECTRIC, BIO_DIESEL }

10.2. Defining the Mapper

Now let's proceed and write our abstract mapper class, that maps Car to CarDTO:

@Mapper public abstract class CarsMapper { @BeforeMapping protected void enrichDTOWithFuelType(Car car, @MappingTarget CarDTO carDto) { if (car instanceof ElectricCar) { carDto.setFuelType(FuelType.ELECTRIC); } if (car instanceof BioDieselCar) { carDto.setFuelType(FuelType.BIO_DIESEL); } } @AfterMapping protected void convertNameToUpperCase(@MappingTarget CarDTO carDto) { carDto.setName(carDto.getName().toUpperCase()); } public abstract CarDTO toCarDto(Car car); }

@MappingTarget is a parameter annotation that populates the target mapping DTO right before the mapping logic is executedin case of @BeforeMapping and right after in case of @AfterMapping annotated method.

10.3. Result

The CarsMapper defined above generatestheimplementation:

@Generated public class CarsMapperImpl extends CarsMapper { @Override public CarDTO toCarDto(Car car) { if (car == null) { return null; } CarDTO carDTO = new CarDTO(); enrichDTOWithFuelType(car, carDTO); carDTO.setId(car.getId()); carDTO.setName(car.getName()); convertNameToUpperCase(carDTO); return carDTO; } }

Notice how the annotated methods invocations surround the mapping logic in the implementation.

11. Support for Lombok

In the recent version of MapStruct, Lombok support was announced. So we can easily map a source entity and a destination using Lombok.

To enable Lombok support we need to add the dependency in the annotation processor path. So now we have the mapstruct-processor as well as Lombok in the Maven compiler plugin:

 org.apache.maven.plugins maven-compiler-plugin 3.5.1  1.8 1.8   org.mapstruct mapstruct-processor 1.3.1.Final   org.projectlombok lombok 1.18.4    

Let's define the source entity using Lombok annotations:

@Getter @Setter public class Car { private int id; private String name; }

And the destination data transfer object:

@Getter @Setter public class CarDTO { private int id; private String name; }

The mapper interface for this remains similar to our previous example:

@Mapper public interface CarMapper { CarMapper INSTANCE = Mappers.getMapper(CarMapper.class); CarDTO carToCarDTO(Car car); }

12. Support for defaultExpression

Starting with version 1.3.0, we can use the defaultExpression attribute of the @Mapping annotation to specify an expression that determines the value of the destination field if the source field is null. This is in addition to the existing defaultValue attribute functionality.

The source entity:

public class Person { private int id; private String name; }

The destination data transfer object:

public class PersonDTO { private int id; private String name; }

Jika field id dari entitas sumber adalah null, kami ingin membuat id acak dan menugaskannya ke tujuan dengan menjaga nilai properti lainnya apa adanya:

@Mapper public interface PersonMapper { PersonMapper INSTANCE = Mappers.getMapper(PersonMapper.class); @Mapping(target = "id", source = "person.id", defaultExpression = "java(java.util.UUID.randomUUID().toString())") PersonDTO personToPersonDTO(Person person); }

Mari tambahkan kasus uji untuk memverifikasi eksekusi ekspresi:

@Test public void givenPersonEntitytoPersonWithExpression_whenMaps_thenCorrect() Person entity = new Person(); entity.setName("Micheal"); PersonDTO personDto = PersonMapper.INSTANCE.personToPersonDTO(entity); assertNull(entity.getId()); assertNotNull(personDto.getId()); assertEquals(personDto.getName(), entity.getName()); }

13. Kesimpulan

Artikel ini memberikan pengantar ke MapStruct. Kami telah memperkenalkan sebagian besar dasar-dasar perpustakaan Pemetaan dan cara menggunakannya dalam aplikasi kami.

Penerapan contoh dan pengujian ini dapat ditemukan di proyek Github. Ini adalah proyek Maven, jadi semestinya mudah untuk mengimpor dan menjalankannya apa adanya.