Skip to content

Commit

Permalink
Merge branch 'release/0.1.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
cardil committed May 7, 2018
2 parents 845442c + 19a8f00 commit 35f7e00
Show file tree
Hide file tree
Showing 66 changed files with 2,997 additions and 17 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# EditorConfig is awesome: http://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
indent_style = space
indent_size = 2
11 changes: 11 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
language: java
script: ./mvnw install --fail-at-end
matrix:
include:
- jdk: openjdk8
env: JACOCO=true COVERALLS=true
- jdk: oraclejdk8
- jdk: oraclejdk9
- jdk: openjdk8
env: GDMSESSION=sonar
- jdk: openjdk8
env: SONAR=publish
165 changes: 154 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,165 @@
# JPA mapping utilities for MapStruct

TODO: write readme file

## Dependencies

* Java >= 7
[![Build Status](https://travis-ci.org/wavesoftware/java-mapstruct-jpa.svg?branch=master)](https://travis-ci.org/wavesoftware/java-mapstruct-jpa) [![Quality Gate](https://sonar.wavesoftware.pl/api/badges/gate?key=pl.wavesoftware.utils:mapstruct-jpa)](https://sonar.wavesoftware.pl/dashboard/index/pl.wavesoftware.utils:mapstruct-jpa) [![Coverage Status](https://coveralls.io/repos/github/wavesoftware/java-mapstruct-jpa/badge.svg?branch=master)](https://coveralls.io/github/wavesoftware/java-mapstruct-jpa?branch=master) [![Maven Central](https://img.shields.io/maven-central/v/pl.wavesoftware.utils/mapstruct-jpa.svg)](https://mvnrepository.com/artifact/pl.wavesoftware.utils/mapstruct-jpa)

A set of utilities focused on mapping JPA managed entities with MapStruct. There are different utilities for different purposes and also a all-in-one utility for maximizing ease of use.

## Features

* Domain model graph with cycles - via `CyclicGraphContext`
* JPA aware mapping with update capability - via `JpaMappingContext` factory
* [N+1 problem](https://stackoverflow.com/questions/97197/what-is-the-n1-select-query-issue) solution via special uninitialized collection classes, that throws exceptions if used

### Domain model graph with cycles

If you need to map a domain model with cycles in entity graph for ex.: (Pet.owner -> Person, Person.pets -> Pet) you can use a `CyclicGraphContext` as a MapStruct `@Context`

```java
@Mapper
interface PetMapper {
Pet map(PetData data, @Context CyclicGraphContext context);
PetData map(Pet pet, @Context CyclicGraphContext context);
}
```

### JPA aware mapping with update capability

If you also need support for mapping JPA managed entities and be able to update them (not create new records) there more to be done. There is provided `JpaMappingContext` with factory. It requires couple more configuration to instantiate this context.

`JpaMappingContext` factory requires:
* Supplier of `StoringMappingContext` to handle cycles - `CyclicGraphContext` can be used here,
* `Mappings` object that will provides mapping for given source and target class - mapping is information how to update existing object (managed entity) with data from source object,
* `IdentifierCollector` should collect managed entity ID from source object

The easiest way to setup all of this is to extend `AbstractJpaContextProvider`, implement `IdentifierCollector` and implement a set of `MappingProvider` for each type of entity. To provide implementations of `MappingProvider` you should create update methods in your MapStruct mappers. It utilize `CompositeContext` which can incorporate any number of contexts as a composite.

All of this can be managed by some DI container like Spring or Guice.

**Mapping facade as Spring service:**

```java
@Service
@RequiredArgsConstructor
final class MapperFacadeImpl implements MapperFacade {

private final PetMapper petMapper;
private final MapStructContextProvider<CompositeContext> contextProvider;

@Override
public PetJPA map(Pet pet) {
return petMapper.map(pet, contextProvider.createNewContext());
}

@Override
public Pet map(PetJPA jpa) {
return petMapper.map(jpa, contextProvider.createNewContext());
}
}
```

**Context provider as Spring service:**

```java
@Service
@RequiredArgsConstructor
final class CompositeContextProvider extends AbstractCompositeContextProvider {

@Getter
private final JpaMappingContextFactory jpaMappingContextFactory;
private final List<MappingProvider<?, ?, ?>> mappingProviders;
@Getter
private final IdentifierCollector identifierCollector;

@Override
protected Iterable<MappingProvider> getMappingProviders() {
return Collections.unmodifiableSet(mappingProviders);
}

}
```

**Example mapping provider for Pet as Spring service:**

```java
@Service
@RequiredArgsConstructor
final class PetMappingProvider implements MappingProvider<Pet, PetJPA, CompositeContext> {

private final PetMapper petMapper;

@Override
public Mapping<Pet, PetJPA, CompositeContext> provide() {
return AbstractCompositeContextMapping.mapperFor(
Pet.class, PetJPA.class,
petMapper::updateFromPet
);
}
}
```

**Identifier collector implementation as Spring service:**

```java
@Service
final class IdentifierCollectorImpl implements IdentifierCollector {
@Override
public Optional<Object> getIdentifierFromSource(Object source) {
if (source instanceof AbstractEntity) {
AbstractEntity entity = AbstractEntity.class.cast(source);
return Optional.ofNullable(
entity.getReference()
);
}
return Optional.empty();
}
}
```

**HINT:** Complete working example in Spring can be seen in [coi-gov-pl/spring-clean-architecture hibernate module](https://github.com/coi-gov-pl/spring-clean-architecture/tree/develop/pets/persistence-hibernate/src/main/java/pl/gov/coi/cleanarchitecture/example/spring/pets/persistence/hibernate/mapper)

**HINT:** An example for Guice can be seen in this repository in test packages.

### N+1 problem solution via special uninitialized collection classes

The N+1 problem is wide known and prominent problem when dealing with JPA witch utilizes lazy loading of data. Solution to this is that developers should fetch only data that they will need (for ex.: using `JOIN FETCH` in JPQL). In many cases that is not enough. It easy to slip some loop when dealing with couple of records.

My solution is to detect that object is not loaded fully and provide a stub that will fail fast if data is not loaded and been tried to be used by other developer. To do that simple use `Uninitialized*` classes provided. There are `UninitializedList`, `UninitializedSet`, and `UninitializedMap`.

```java
@Mapper
interface PetMapper {
// [..]
default List<Pet> petJPASetToPetList(Set<PetJPA> set,
@Context CompositeContext context) {
if (!Hibernate.isInitialized(set)) {
return new UninitializedList<>(PetJPA.class);
}
return set.stream()
.map(j -> map(j, context))
.collect(Collectors.toList());
}
// [..]
}
```

**Disclaimer:** In future we plan to provide an automatic solution using dynamic proxy objects.

## Dependencies

* Java >= 8
* [MapStruct JDK8](https://github.com/mapstruct/mapstruct/tree/master/core-jdk8) >= 1.2.0
* [EID Exceptions](https://github.com/wavesoftware/java-eid-exceptions) library
### Contributing

### Contributing

Contributions are welcome!

To contribute, follow the standard [git flow](http://danielkummer.github.io/git-flow-cheatsheet/) of:

1. Fork it
1. Create your feature branch (`git checkout -b feature/my-new-feature`)
1. Commit your changes (`git commit -am 'Add some feature'`)
1. Push to the branch (`git push origin feature/my-new-feature`)
1. Create new Pull Request

Even if you can't contribute code, if you have an idea for an improvement please open an [issue](https://github.com/wavesoftware/java-mapstruct-jpa/issues).
53 changes: 47 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

<groupId>pl.wavesoftware.utils</groupId>
<artifactId>mapstruct-jpa</artifactId>
<version>0.1.0-SNAPSHOT</version>
<version>0.1.0</version>
<packaging>jar</packaging>

<name>JPA mapping utilities for MapStruct</name>
Expand Down Expand Up @@ -67,7 +67,7 @@
<sonar.working.directory>${project.build.directory}/sonar</sonar.working.directory>
<sonar.host.url>https://sonar.wavesoftware.pl</sonar.host.url>
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<java.source.version>7</java.source.version>
<java.source.version>8</java.source.version>
<sonar.java.source>${java.source.version}</sonar.java.source>
<maven.compiler.source>1.${java.source.version}</maven.compiler.source>
<maven.compiler.target>${maven.compiler.source}</maven.compiler.target>
Expand All @@ -80,10 +80,12 @@
</properties>

<dependencies>
<!-- provided -->
<dependency>
<groupId>pl.wavesoftware</groupId>
<artifactId>eid-exceptions</artifactId>
<version>1.2.0</version>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
Expand All @@ -92,7 +94,28 @@
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>[1.2.0.Final,2.0.0)</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>[1.2.0.Final,2.0.0)</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>

<!-- runtime -->
<dependency>
<groupId>pl.wavesoftware</groupId>
<artifactId>eid-exceptions</artifactId>
<version>1.2.0</version>
</dependency>

<!-- test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand All @@ -102,7 +125,25 @@
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>2.5.0</version>
<version>3.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.18.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.17.Final</version>
<scope>test</scope>
</dependency>
</dependencies>
Expand Down
54 changes: 54 additions & 0 deletions src/main/java/pl/wavesoftware/lang/TriConsumer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package pl.wavesoftware.lang;

import java.util.Objects;
import java.util.function.Consumer;

/**
* Represents an operation that accepts tree input arguments and returns no
* result. This is the tree-arity specialization of {@link Consumer}.
* Unlike most other functional interfaces, {@code TriConsumer} is expected
* to operate via side-effects.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #accept(Object, Object, Object)}.
*
* @param <T> the type of the first argument to the operation
* @param <U> the type of the second argument to the operation
* @param <V> the type of the third argument to the operation
*
* @see Consumer
* @author <a href="mailto:krzysztof.suszynski@wavesoftware.pl">Krzysztof Suszynski</a>
* @since 25.04.18
*/
@FunctionalInterface
public interface TriConsumer<T, U, V> {
/**
* Performs this operation on the given arguments.
*
* @param t the first input argument
* @param u the second input argument
* @param v the third input argument
*/
void accept(T t, U u, V v);

/**
* Returns a composed {@code TriConsumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code TriConsumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default TriConsumer<T, U, V> andThen(TriConsumer<? super T, ? super U, ? super V> after) {
Objects.requireNonNull(after);

return (f, s, t) -> {
accept(f, s, t);
after.accept(f, s, t);
};
}
}
8 changes: 8 additions & 0 deletions src/main/java/pl/wavesoftware/lang/package-info.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* @author <a href="mailto:krzysztof.suszynski@wavesoftware.pl">Krzysztof Suszyński</a>
* @since 2018-05-03
*/
@ParametersAreNonnullByDefault
package pl.wavesoftware.lang;

import javax.annotation.ParametersAreNonnullByDefault;
Loading

0 comments on commit 35f7e00

Please sign in to comment.