In this example, we’ll make the implement small Microservices POC using Spring Cloud API Gateway, Eureka and Spring Cloud. In this example, we will show to configure routes by making the use Spring Cloud API Gateway

In this diagram, I’ve shows two microservices (User Service and Account Management), but focused on single microservices to show the intelligent routing can be done using Spring Cloud API Gateway. For now there is no database is used in the code, but in future tutorials I will do that.

Service Discovery

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>…


ItemReader — Strategy interface for providing the data. Implementations are expected to be stateful and will be called multiple times for each batch, with each call to read() returning a different value and finally returning null when all input data is exhausted. Implementations need not be thread-safe and clients of a ItemReader need to be aware that this is the case. A richer interface (e.g. with a look ahead or peek) is not feasible because we need to support transactions in an asynchronous batch.

SimpleItemReader.java

public class SimpleItemReader implements ItemReader<String> {

private List<String> dataSet =…

This application is a proof of concept for using Spring Projections(DTO) and cross joins written via JPQL and native SQL (for MySQL).

Key points:

  • define two entities (e.g., Book and Format )
  • write interfaces (Spring projections) that contains getters for the columns that should be fetched from the database ( e.g., check BookTitleAndFormatType.java)
  • write cross joins queries using JPQL/SQL

Book.java

@Data
@Entity
public class Book implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String title;
private String isbn;
}

Format.java

@Data
@Entity
public class Format implements Serializable {

private…

In this example, we’ll see how to make the use of Spring batch decider with the various transitions.

MainApp.java

@SpringBootApplication
@EnableBatchProcessing
@RequiredArgsConstructor
public class DeciderApplication {

private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;

@Bean
public DeliveryDecider decider(){
return new DeliveryDecider();
}

@Bean
public Step leaveAtDoorStep() {
return this.stepBuilderFactory.get("leaveAtDoorStep").tasklet((contribution, chunkContext) -> {
System.out.println(">>>> Leaving the package at the door.");
return RepeatStatus.FINISHED

This application is an example of retrieving the database auto-generated primary keys.

Key points:

  • JPA style, retrieve the auto-generated keys via getId()
  • JDBC style, retrieve the auto-generated keys via JdbcTemplate
  • JDBC style, retrieve the auto-generated keys via SimpleJdbcInsert

Author.java

@Data
@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private int age;
private String name;
private String genre;
}

AuthorRepository.java

@Repository
public interface AuthorRepository extends JpaRepository<Author, Long> {
}

AuthorDao.java

public interface AuthorDao {
public long insertAuthor(int age, String name, String genre);
}

JdbcTemplateDao.java

@RequiredArgsConstructor
@Repository
public class JdbcTemplateDao implements…

This application is a sample of reusing an interface-based Spring projection. This is useful to avoid defining multiple interface-based Spring projections in order to cover a range of queries that fetches different subsets of fields.

Key points:

  • define an interface-based Spring projection containing getters for the wider case.
  • rely on class-level @JsonInclude(JsonInclude.Include.NON_DEFAULT) annotation to avoid serialization of default fields (e.g., fields that are not available in the current projection and are null - these fields haven't been fetched in the current query)
  • this is useful to Jackson that will not serialize in the resulted JSON the missing fields (e.g.,

Description: Fetching more data than needed is prone to performance penalities. Using DTO allows us to extract only the needed data. In this application we rely on constructor and Spring Data Query Builder Mechanism.

Key points:

  • write a proper constructor in the DTO class
  • rely on Spring Data Query Builder Mechanism to write the SQL
  • for using Spring Data Projections check this item.

Author.java

@Data
@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private int age;
private String name;
private String genre;
}

AuthorRepository.java

@Repository
public interface AuthorRepository…

Description: Hibernate Types is a set of extra types not supported by default in Hibernate Core. One of these types is java.time.YearMonth. This is a Spring Boot application that uses Hibernate Type to store this YearMonth in a MySQL database as integer or date.

Key points:

  • for Maven, add Hibernate Types as a dependency in pom.xml
  • in entity use @TypeDef to map typeClass to defaultForType

Book.java

@Data
@Entity
@TypeDef(
typeClass = YearMonthIntegerType.class, // or, YearMonthDateType
defaultForType = YearMonth.class
)

public class Book implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) …

This application is meant to highlight that the best place to use @Transactional for user defined query-methods is in repository interface, and afterwards, depending on situation, on service-methods level.

Author.java

@Data
@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
private Long id;

private int age;
private String name;
private String genre;
}

AuthorRepository.java

@Repository
@Transactional(readOnly = true)
public interface AuthorRepository extends JpaRepository<Author, Long> {

@Query("SELECT a FROM Author a WHERE a.name = ?1")
public Author fetchByName(String name);

@Transactional
@Modifying
@Query("DELETE FROM Author a WHERE a.genre <> ?1")

public int deleteByNeGenre(String genre);
}

BookStoreService.java


Hibernate Types is a library of extra types not supported by Hibernate Core by default. This is a Spring Boot application that uses this library to persist JSON data (JSON Java Object) in a PostgreSQL json column and for querying JSON data from the PostgreSQL json column to JSON Java Object. Updates are supported as well.

Key points:

  • for Maven, add Hibernate Types as a dependency in pom.xml
  • in entity use @TypeDef to map typeClass to JsonBinaryType

Book.java

@Data
public class Book implements Serializable {

private static final long serialVersionUID = 1L;

private…

Prateek Ashtikar

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store