Panduan Pantas untuk MapStruct

1. Gambaran keseluruhan

Dalam artikel ini, kita akan meneroka penggunaan MapStruct yang, sederhana, mapper Java Bean.

API ini mengandungi fungsi yang secara otomatis memetakan antara dua kacang Jawa. Dengan MapStruct kita hanya perlu membuat antara muka, dan perpustakaan secara automatik akan membuat pelaksanaan konkrit selama waktu kompilasi.

2. Corak Objek Peta Peta dan Pindah

Untuk kebanyakan aplikasi, anda akan melihat banyak kod plat boiler yang menukar POJO ke POJO lain.

Sebagai contoh, jenis penukaran yang biasa berlaku antara entiti yang disokong kegigihan dan DTO yang keluar ke pihak pelanggan.

Jadi itulah masalah yang diselesaikan oleh MapStruct - membuat pemetik kacang secara manual memakan masa. Perpustakaan dapat menjana kelas pemetik kacang secara automatik .

3. Maven

Mari tambahkan kebergantungan di bawah ke dalam Maven pom.xml kami :

 org.mapstruct mapstruct 1.3.1.Final 

Pelepasan terbaru Mapstruct yang stabil dan pemprosesnya boleh didapati dari Maven Central Repository.

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

The mapstruct pemproses digunakan untuk menjana pelaksanaan mapper semasa membina:

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

4. Pemetaan Asas

4.1. Membuat POJO

Mari kita buat Java POJO ringkas:

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. Antaramuka Mapper

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

Notis kita tidak mewujudkan kelas pelaksanaan bagi kami SimpleSourceDestinationMapper - kerana MapStruct mencipta untuk kita.

4.3. Pemetaan Baru

Kita boleh mencetuskan pemprosesan MapStruct dengan melakukan pemasangan bersih mvn .

Ini akan menghasilkan kelas pelaksanaan di bawah / target / dihasilkan-sumber / anotasi / .

Inilah kelas yang dibuat secara automatik oleh MapStruct untuk kami:

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. Kes Ujian

Akhirnya, dengan semua yang dihasilkan, mari tulis kes ujian akan menunjukkan bahawa nilai dalam SimpleSource sesuai 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 Suntikan Ketergantungan

Seterusnya, mari dapatkan contoh mapper di MapStruct dengan hanya memanggil Mappers.getMapper (YourClass.class).

Sudah tentu, itu adalah cara yang sangat manual untuk mendapatkan contoh - alternatif yang lebih baik adalah menyuntikkan mapper secara langsung di mana kita memerlukannya (jika projek kita menggunakan penyelesaian Dependency Injection).

Nasib baik MapStruct mempunyai sokongan padu untuk Spring dan CDI ( Konteks dan Suntikan Ketergantungan ).

Untuk menggunakan Spring IoC dalam mapper kami, kami perlu menambahkan atribut komponenModel ke @Mapper dengan nilai spring dan untuk CDI adalah cdi .

5.1. Ubah suai Mapper

Tambahkan kod berikut ke SimpleSourceDestinationMapper :

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

6. Memetakan Medan Dengan Nama Medan Yang Berbeza

Dari contoh sebelumnya, MapStruct dapat memetakan kacang kami secara automatik kerana mereka mempunyai nama bidang yang sama. Jadi bagaimana jika kacang yang hendak kita petakan mempunyai nama bidang yang berbeza?

Sebagai contoh, kami akan mencipta kacang baru yang disebut Employee and 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. Antaramuka Mapper

Semasa memetakan nama bidang yang berbeza, kita perlu mengkonfigurasi bidang sumbernya ke bidang sasarannya dan untuk melakukan itu kita perlu menambahkan anotasi @Mappings . Anotasi ini menerima pelbagai anotasi @Mapping yang akan kami gunakan untuk menambahkan atribut target dan source.

Dalam MapStruct kita juga dapat menggunakan notasi titik untuk menentukan 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. Kes Ujian

Sekali lagi kita perlu menguji bahawa kedua-dua nilai objek sumber dan tujuan sepadan:

@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()); }

Lebih banyak kes ujian boleh didapati dalam projek Github.

7. Memetakan Kacang Dengan Kacang Kanak-kanak

Seterusnya, kami akan menunjukkan cara memetakan kacang dengan merujuk kepada kacang lain.

7.1. Ubah suai POJO

Mari tambahkan rujukan kacang baru ke objek Pekerja :

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 suai 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; }

Sekiranya medan id entiti sumber kosong, kami ingin menghasilkan id rawak dan memberikannya ke destinasi dengan mengekalkan nilai harta benda lain seperti:

@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 kes ujian untuk mengesahkan pelaksanaan 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. Kesimpulannya

Artikel ini memberikan pengenalan kepada MapStruct. Kami telah memperkenalkan sebahagian besar asas perpustakaan Pemetaan dan cara menggunakannya dalam aplikasi kami.

Pelaksanaan contoh dan ujian ini boleh didapati dalam projek Github. Ini adalah projek Maven, jadi mudah untuk diimport dan dijalankan sebagaimana adanya.