Skip to content

JPA Repositories with Specification

Furkan Kürşat Danışmaz edited this page Sep 11, 2018 · 7 revisions

Source Folder: jpa-specification

Tech Stack:

  • spring-boot
  • spring-mvc
  • spring-data
  • hibernate & hibernate metamodel generator
  • postgresql
  • hibernate-c3p0
  • mapstruct (for model transformation)
  • log4j2 (slf4j impl)
  • project lombok

This is a ready-to-use Maven Java project template with the libraries listed above.

Problems Solved

  • ORM with hibernate
  • Logging with Slf4j with Log4J2
  • Monitoring entities with Spring Data and AuditorAware (@CreatedBy, @CreatedDate, @LastModifiedBy, @LastModifiedDate)
  • Connection pooling C3P0
  • Model mapping (without reflection) with MapStruct
  • Passing LocalDate & LocalDateTime from Client to an endpoint (jackson-datatype-jsr310.jar needed for this)
  • Using JPA specification API instead of writing Query

Passing LocalDate & LocalDateTime from Client to Controller

Steps:

  1. Add the following dependency:
<dependency>
	<groupId>com.fasterxml.jackson.datatype</groupId>
	<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
  1. Add @JsonFormat to your LocalDate / LocalDateTime field
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")
private LocalDate birthdate;

You are ready to go.

Using Hibernate Metamodel for Type Safety

Just add the following maven plugin and maven will automatically generate Hibernate Metamodel under "generated-sources"

<plugin>
	<groupId>org.bsc.maven</groupId>
	<artifactId>maven-processor-plugin</artifactId>
	<version>3.2.0</version>
	<executions>
		<execution>
			<id>process</id>
			<goals>
				<goal>process</goal>
			</goals>
			<phase>generate-sources</phase>
			<configuration>
				<processors>
					<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
				</processors>
				<outputDirectory>target/generated-sources/annotations</outputDirectory>
			</configuration>
		</execution>
	</executions>
	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-jpamodelgen</artifactId>
			<version>${hibernate.jpamodelgen-version}</version>
		</dependency>
	</dependencies>
</plugin>

Clone this wiki locally