Coder Social home page Coder Social logo

mapstruct-eclipse's Introduction

MapStruct - Java bean mappings, the easy way!

Latest Stable Version Latest Version License

Build Status Coverage Status Gitter Code Quality: Java Total Alerts

What is MapStruct?

MapStruct is a Java annotation processor for the generation of type-safe and performant mappers for Java bean classes. It saves you from writing mapping code by hand, which is a tedious and error-prone task. The generator comes with sensible defaults and many built-in type conversions, but it steps out of your way when it comes to configuring or implementing special behavior.

Compared to mapping frameworks working at runtime, MapStruct offers the following advantages:

  • Fast execution by using plain method invocations instead of reflection
  • Compile-time type safety. Only objects and attributes mapping to each other can be mapped, so there's no accidental mapping of an order entity into a customer DTO, etc.
  • Self-contained code—no runtime dependencies
  • Clear error reports at build time if:
    • mappings are incomplete (not all target properties are mapped)
    • mappings are incorrect (cannot find a proper mapping method or type conversion)
  • Easily debuggable mapping code (or editable by hand—e.g. in case of a bug in the generator)

To create a mapping between two types, declare a mapper interface like this:

@Mapper
public interface CarMapper {

    CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );

    @Mapping(target = "seatCount", source = "numberOfSeats")
    CarDto carToCarDto(Car car);
}

At compile time MapStruct will generate an implementation of this interface. The generated implementation uses plain Java method invocations for mapping between source and target objects, i.e. no reflection is involved. By default, properties are mapped if they have the same name in source and target, but you can control this and many other aspects using @Mapping and a handful of other annotations.

Requirements

MapStruct requires Java 1.8 or later.

Using MapStruct

MapStruct works in command line builds (plain javac, via Maven, Gradle, Ant, etc.) and IDEs.

For Eclipse, a dedicated plug-in is in development (see https://github.com/mapstruct/mapstruct-eclipse). It goes beyond what's possible with an annotation processor, providing content assist for annotation attributes, quick fixes and more.

For IntelliJ the plug-in is available within the IntelliJ marketplace (see https://plugins.jetbrains.com/plugin/10036-mapstruct-support).

Maven

For Maven-based projects, add the following to your POM file in order to use MapStruct (the dependencies are available at Maven Central):

...
<properties>
    <org.mapstruct.version>1.5.5.Final</org.mapstruct.version>
</properties>
...
<dependencies>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>${org.mapstruct.version}</version>
    </dependency>
</dependencies>
...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${org.mapstruct.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>
...

Gradle

For Gradle, you need something along the following lines:

plugins {
    ...
    id "com.diffplug.eclipse.apt" version "3.26.0" // Only for Eclipse
}

dependencies {
    ...
    implementation 'org.mapstruct:mapstruct:1.5.5.Final'

    annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.5.Final'
    testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.5.5.Final' // if you are using mapstruct in test code
}
...

If you don't work with a dependency management tool, you can obtain a distribution bundle from Releases page.

Documentation and getting help

To learn more about MapStruct, refer to the project homepage. The reference documentation covers all provided functionality in detail. If you need help please ask it in the Discussions.

Building from Source

MapStruct uses Maven for its build. Java 11 is required for building MapStruct from source. To build the complete project, run

./mvnw clean install

from the root of the project directory. To skip the distribution module, run

./mvnw clean install -DskipDistribution=true

Importing into IDE

MapStruct uses the gem annotation processor to generate mapping gems for its own annotations. Therefore, for seamless integration within an IDE annotation processing needs to be enabled.

IntelliJ

Make sure that you have at least IntelliJ 2018.2.x (needed since support for annotationProcessors from the maven-compiler-plugin is from that version). Enable annotation processing in IntelliJ (Build, Execution, Deployment -> Compiler -> Annotation Processors)

Eclipse

Make sure that you have the m2e_apt plugin installed.

Links

Licensing

MapStruct is licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0.

mapstruct-eclipse's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mapstruct-eclipse's Issues

Add a unit-testing infrastructure

Currently we don't have an infrastructure for unit-testing the mapstruct-eclipse plugin. We should change that at some point... 😉

Refactoring support

When a bean property getter/setter is refactored, any references in @Mapping#source() or target() should be updated as well.

Jenkins down

The Eclipse download seems offline. There's only a message that says jenkins is hybernated.

Eclipse Marketplace listing

We definitely should think about to list a more mature version of the MapStruct plug-in on the Eclipse Marketplace.

Eclipse 2018-12RC1 - incremental compilation fails with APT

Eclipse 2018-12RC1 run on OpenJDK 11. Target project is Java 8 or Java 11. I guess any target will work the same.

In pom.xml:
<m2e.apt.activation>jdt_apt</m2e.apt.activation>

	<dependency>
		<groupId>org.mapstruct</groupId>
		<artifactId>mapstruct-jdk8</artifactId>
		<version>1.2.0.Final</version>
	</dependency>
	<dependency>
		<groupId>org.mapstruct</groupId>
		<artifactId>mapstruct-processor</artifactId>
		<version>1.2.0.Final</version>
		<scope>provided</scope>
	</dependency>

When I change any of a mapped class or a mapping interface the interface gets error marker with the stack trace below:

Internal error in the mapping processor: java.lang.RuntimeException: javax.annotation.processing.FilerException: Source file already exists : test.mapstruct.TestMapperImpl at org.mapstruct.ap.internal.processor.MapperRenderingProcessor.createSourceFile(MapperRenderingProcessor.java:71) at org.mapstruct.ap.internal.processor.MapperRenderingProcessor.writeToSourceFile(MapperRenderingProcessor.java:52) at org.mapstruct.ap.internal.processor.MapperRenderingProcessor.process(MapperRenderingProcessor.java:42) at org.mapstruct.ap.internal.processor.MapperRenderingProcessor.process(MapperRenderingProcessor.java:37) at org.mapstruct.ap.MappingProcessor.process(MappingProcessor.java:280) at org.mapstruct.ap.MappingProcessor.processMapperTypeElement(MappingProcessor.java:260) at org.mapstruct.ap.MappingProcessor.processMapperElements(MappingProcessor.java:226) at org.mapstruct.ap.MappingProcessor.process(MappingProcessor.java:162) at org.eclipse.jdt.internal.compiler.apt.dispatch.RoundDispatcher.handleProcessor(RoundDispatcher.java:142) at org.eclipse.jdt.internal.compiler.apt.dispatch.RoundDispatcher.round(RoundDispatcher.java:124) at org.eclipse.jdt.internal.compiler.apt.dispatch.BaseAnnotationProcessorManager.processAnnotations(BaseAnnotationProcessorManager.java:174) at org.eclipse.jdt.internal.apt.pluggable.core.dispatch.IdeAnnotationProcessorManager.processAnnotations(IdeAnnotationProcessorManager.java:138) at org.eclipse.jdt.internal.compiler.Compiler.processAnnotations(Compiler.java:940) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:450) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:426) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:386) at org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder.compile(IncrementalImageBuilder.java:371) at org.eclipse.jdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:318) at org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder.incrementalBuildLoop(IncrementalImageBuilder.java:186) at org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder.build(IncrementalImageBuilder.java:143) at org.eclipse.jdt.internal.core.builder.JavaBuilder.buildDeltas(JavaBuilder.java:281) at org.eclipse.jdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:202) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:833) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:220) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:263) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:316) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:319) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:371) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:392) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:154) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:244) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) Caused by: javax.annotation.processing.FilerException: Source file already exists : test.mapstruct.TestMapperImpl at org.eclipse.jdt.internal.apt.pluggable.core.filer.IdeFilerImpl.createSourceFile(IdeFilerImpl.java:177) at org.mapstruct.ap.internal.processor.MapperRenderingProcessor.createSourceFile(MapperRenderingProcessor.java:68) ... 33 more

No Code completions anymore?

I'm hesitant to post this as issues like this tend to be a misconfig somewhere...

I'm no longer getting any code completions at all from MapStruct. I initially thought this was because we used records almost exclusively everywhere, but now I tried to create a simple POJO and that offers no code completions for @Mapping either.

Eclipse 2023-09, MapStruct Tools 0.1.0.201701192129. The error log seems clear. Enabling or disabling "Enable non-blocking completions" makes no difference.

Example code:

@Mapper
public interface AhaMapper {
    @Mapping(target = "name", source = "name2")
    Aha fromDto2(Aha2 ahaaa);
}

public static class Aha {
    private final String name;

    public Aha(String name) {
        this.name = name;
    }

    public String getName() { return name; }
}

public static class Aha2 {
    private final String name2;

    public Aha2(String name2) {
        this.name2 = name2;
    }

    public String getName2() { return name2; }
}

Documentation

Much more documentation is needed:

  • Functionality overview
  • How to install
  • How to setup the preferences
  • ...

Eclipse 2019-12 - incremental compilation fails with APT

We're using Eclipse 2019-12 and Mapstruct 1.3.1.Final.
Same issue as #43
This seems related to ecj compiler since we have the same issue with intellij when using ecj compiler instead of the javac compiler.
This issue is really annoying since we have to rebuild the whole project each time that we have a new mapping with mapstruct.

@Qualifier behavior not working with object

Consider the Mapper :

@GearQualifier
public abstract class GearSpecMapper {

   @GearDTO1Qualifier
   public GearDTO1 toDTO1(GearSpec entity) {
     return ... // some mapping logic
   }

   @GearDTO2Qualifier
   public GearDTO2 toDTO2(GearSpec entity) {
     return ... // some mapping logic
   }

}

And my main mapper

@Mapper(uses=GearQualifier.class)
public interface GearSpecMapper {

  @Mapping(target="gearDTO", source="gear", qualifiedBy={GearQualifier.class, GearDTO1Qualifier.class})
   EngineDTO1 fromEntity(Entity entity);

}

All my @Gear*Qualifier are @Qualifier with propeper retention

I get an error saying my mapping is ambigious and he quotes that he cannot choose beetween the two method of my GearSpecMapper

In the documentation the only example shown with @Qualifier is used mapping a String to a String. Is using this a limitation (no mapping object supported )?
Did I miss something.
I used a decorator as a workaround.

Cheers,

PS : love the framework otherwise ;-), great work !

Provide navigation support when clicking annotation members

When hovering with the cursor over or CRTL+clicking certain annotation members, it'd be great to get a) a tooltip with more information (type, full signature) and b) jumping to the declaration of that element:

  • @Mapping#source() / target()
  • @InheritConfiguration#name()
  • ...

Hey @larswetzer, WDYT, is it doable?

support non blocking completion

In Eclipse non blocking completion is disabled when using the mapstruct eclipse plugin.
Would be great if that could be implemented in the plugin.
image

Allow to set-up MapStruct for Java projects through the plug-in

When working with a Maven project for which MapStruct is enabled (e.g. through via maven-processor-plugin), upon import of the project M2E will automatically configure the Eclipse project to run the MapStruct annotation processor.

But for plain "Java Project"s it'd be nice if the plug-in could be used to set up MapStruct. It could like this:

  • Under "Project Properties" have an entry "MapStruct"
  • On that page have a check box "Enable MapStruct for this project"; When checked this should register the annotation processor (AFAIK there is an extension point through which APs can be registered)
  • Allow to specify the processor options through check boxes as well
  • Optionally, have a global preferences pane which can be used to configure default values for the processor options which would be overridden by project-scoped settings

@larswetzer WDYT, would that make sense?

Plugin installation : Unable to read repository

Hello,

When installing the plugin from mapstruct website or from eclipse marketplace, I have this error in eclipse:

Unable to read repository at https://mapstruct.org/eclipse/content.xml.
Certificate for <mapstruct.org> doesn't match any of the subject alternative names: [*.github.com, www.github.com, github.io, github.com, *.github.io, githubusercontent.com, *.githubusercontent.com]

Can you look into it ?

I searched a little the website repository and found that there is no content.xml file in the static/eclipse folder, maybe it is related ? (I don't know anything about how to deploy and develop an eclipse plugin).

Quick-Fix: Handle message "Can't map property x to y. Consider to declare ..."

The following error message:

Can't map property "org.foobar.OtherType prop3" to "org.foobar.SomeType prop3". Consider to declare/implement a mapping method: "org.foobar.SomeType map(org.foobar.OtherType value)".

... could use a quick-fix to either ignore the property, or to add a method with the suggested signature.

Some more auto-completions

  • In @Mapper#componentModel() there could be shown the list of supported values
  • In @Mapper#config() there could be shown a filtered list only containing actual config classes
  • In @InheritConfiguration#name()/@InheritInverseConfiguration#name() there could be shown a filtered list of existing method names - handled in #22
  • @Mapper#dependsOn() should suggest only properties of the target bean - handled in #23

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.