Java Maven using MapStruct (NetBeans IDE)
package com.medibank.javamavenmapstruct.source_dest_example
- SimpleDestination.java
- SimpleSource.java
- SimpleSourceDestinationMapper.java
Note: Ignore the error indicator in Netbeans (Bug)
Step 1 - Do a clean and build the project
Step 2 - Run a test
Note: No need to create this file because it's automatically created when you compile in the target/generated-sources/
package com.medibank.javamavenmapstruct.source_dest_example; import javax.annotation.processing.Generated; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2024-03-04T09:53:13+1100", comments = "version: 1.5.5.Final, compiler: javac, environment: Java 11.0.22 (Amazon.com Inc.)" ) 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; } }
- Student.java
- StudentEntity.java
- StudentMapper.java
StudentMapper.java
package com.medibank.javamavenmapstruct.student; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @Mapper public interface StudentMapper { @Mapping(target="className", source="classVal") Student getModelFromEntity(StudentEntity student); @Mapping(target="classVal", source="className") StudentEntity getEntityFromModel(Student student); }
package student; import com.medibank.javamavenmapstruct.student.Student; import com.medibank.javamavenmapstruct.student.StudentEntity; import com.medibank.javamavenmapstruct.student.StudentMapper; import static junit.framework.Assert.assertEquals; import org.junit.Test; import org.mapstruct.factory.Mappers; public class StudentMapperTest { private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class); @Test public void testEntityToModel() { StudentEntity entity = new StudentEntity(); entity.setClassVal("X"); entity.setName("John"); entity.setId(1); Student model = studentMapper.getModelFromEntity(entity); assertEquals(entity.getClassVal(), model.getClassName()); assertEquals(entity.getName(), model.getName()); assertEquals(entity.getId(), model.getId()); } @Test public void testModelToEntity() { Student model = new Student(); model.setId(1); model.setName("John"); model.setClassName("X"); StudentEntity entity = studentMapper.getEntityFromModel(model); assertEquals(entity.getClassVal(), model.getClassName()); assertEquals(entity.getName(), model.getName()); assertEquals(entity.getId(), model.getId()); } }