JPA One to One Mapping Example with Spring Boot

In this tutorial, I will explain how to define one to one relationship between two entities using JPA.

For instance we have a Person table and a License table.A Person table is associated with a single License and vice versa.Hence, Person and License table have one to one relationship with each other.

The License Account table looks like this:-

CREATE TABLE License (
expiryDate Date ,
startDate Date,
licenseId NUMBER(4) PRIMARY KEY
);

The Person table is linked with licenseId which is a foreign key in License table.

CREATE TABLE Person (
firstName varchar(50),
lastName varchar(50),
email varchar(50) ,
personId NUMBER(4) PRIMARY KEY,
licenseId NUMBER(4),
FOREIGN KEY (licenseId) REFERENCES License(licenseId)
);

Prerequsites :-

  • Spring Boot Project
  • Maven 3

To create a spring boot project you an follow this tutorial.

Now we will create the Person Entity.

Please note the annotations added for the Person POJO.We have the @JoinColumn annotation which specifies that the Person entity is linked with License entity by licenseId in database.We specifically add the name attribute to provide the foreign key (licenseId) in Person table..Then we have @OneToOne annotation which specifies that the Person and License has one to one relationship.We also specify the cascade and fetch strategy .FetchType can be Eager or Lazy. We have specified eager so that License object is also fetched with Person Object every time we make a call to fetch Person details.

By CascadeType all means all the CRUD operations performed on Person object will propagate to License object.

We will now create License entity.Note the @OneToOne annotation, it specifies the mappedBy attribute and it should refer to the license object specified in Person entity.

There are also two more annotations used here which is @JsonManagedReference and @JsonBackReference in Person and License object.I have added this to avoid the JSON infinite recursion error.If you dont add these annotations you might get the following error while fetching the person object:-

org.springframework.http.converter.HttpMessageNotWritableException”,”message”:”Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) 

Now we will create PersonRepository .It will extend the JpaRepository.

We will create PersonService and PersonServiceImpl.

Implementing the methods in the interfaces:-

Now we will create the controller:-

Run the Spring Boot application (Right click -> Run DemoApplication):-

When you start the application , it will show up in the logs like this:-

Testing the application from postman (Saving Person):-

Fetching the Person and License object which we just saved.

When you run the above postman calls you will see the insert and select statements in the console.

You will see the records created in the Person table.

Record created in License Table

That’s all on one to one mapping in Spring JPA .I hope you liked this article.

Happy Coding 🙂

Spring Batch (Reading Data from DB Table)

Spring Batch is basically used to process or automate a job which can be scheduled to run at a date and time as per the given cron schedule.In this tutorial I will explain how to create a spring batch which can read data from a database table and process it.

In my previous tutorial ,I explained about the Spring Batch and how to read data from a csv and write it to a database table.

Prerequisite

  • Maven3
  • IntelliJ

The use case is to read from the following database table:-

Partner_Program_Fee

partnerId number(13,0)

programName varchar(35)

startDate Date

endDate Date

Create a new project in IntelliJ. Project Structure:-

Create a POJO for the table called PartnerProgramFee.

Now ,we will create a mapper for reading from the database table.The mapper is used to map the data read from the sql to our Pojo class.Our custom mapper implements RowMapper which will map the rows returned from sql statement to our Pojo class.

Spring batch mapper

There are three parts to any Spring Batch:-

  • Reader
  • Processor
  • Writer

And we will declare all these three components as beans in our Batch Job configuration.

Reader:- We need a JdbcCursorItemReader to read data from the database.

We provide a native sql query in our Reader(partnerProgramFeeReader) and in the rowMapper we provide the PartnerProgramFeeMapper which we created for mapping the data returned from sql to our Pojo class.We also need to assign dataSource to the JdbcCursorItemReaderBuilder. You can use this tutorial to configure datasource in your spring batch.

Processor:- In our custom processor we implement the ItemProcessor.You can process/update the data we got from the mapper in the processor.This is where usually we have the business logic.

Writer:- Writer is used to either write data to a csv or a database table or call a service.In out tutorial we are primarily focusing on reading data from database so I am not doing anything in the writer class.But I have added the writer code to show how it looks .You create your own custom writer by implementing ItemWriter.

Now, we will create the Spring Batch Configuration to declare the reader, processor and writer as beans.There are five parts to Spring Batch Configuration:-

  • Job Builder Factory
  • Step Builder Factory
  • Data Source
  • Declaring Beans for reader, processor and writer
  • Declaring the Spring Batch Job by using the above specified components.

Here’s the code:-

Please note the annotations you need to include in your Spring Batch Configuration.

Declaring the reader, processor and writer.

Declaring the Step and the Job:-

The last step is to create a Batch Job executor to run the job.

Please note the annotation you need to add in the Batch Job Executor

Launching the job in the batch job executor:-

You can specify the cron schedular in the application property file and read it in the batch job executor.Example:-

partner.program.fee.batch.cron=0 */5 * * * ?
The above cron will execute the job every 5 minutes.

When you start the batch job the job should run every 5 minutes .

That’s all about reading from data in a Spring Batch job.

Happy Coding 🙂

Spring JPA Beginner Tutorial

In this tutorial I will explain how to build a basic Spring JPA project using Spring Initilizr.

Core Concept

The goal of spring data repository is to significantly reduce the amount of boiler plate code required to implement the persistence/dao layer in any Spring application.

The primary interface in Spring data repository abstraction is Repository.It is a marker interface ,it takes the domain class as well as the id of the domain class as type arguments.The CRUDRepository which extends the Repository interface provided more sophisticated CRUD functionality for the entity/domain class. On top of CRUDRepository there is PagingAndSortingRepository abstraction that provides additional methods to ease pagination access to entities.

Now ,lets create a Spring JPA project using Spring Initialzr.

While creating a project through Spring Initialzr select the following options and click on generate button:-

You need to select Spring Data JPA,Spring Web and H2 Database which is an in memory database.

When you click on generate a a zip file will be saved in your machine.Unzip the folder and the maven project can be imported in IntelliJ or any other IDE.Click on Import Project ,navigate to the location where you project is saved (where the primary pom file is located).

Click on open and the project will be imported in Intellij.

Here’s the project:-

We will create a set of REST API’s for creating, updating and deleting employees.

We will first create a domain object named Employee.We will annotate with @Entity annotation. To declare the primary we annotate the variable with @Id annotation.

The Employee object has a set of variables along with the getter/setter methods.

Next we will create the Repository interface to perform operations on this Employee object.

Our custom interface extends the JpaRepository. The Jpa repository contains methods to perform CRUD operations.We need to pass the domain object and type of the primary variable in the domain object.

Next we create a service interface and the service implementation.

Next we provide the implementation for EmployeeService .We annotate the EmployeeServiceImpl with @Service annotation. In the employee service implementation we refer the EmployeeRepository using the @Autowired annotation.

In the above EmployeeServiceImpl we call the CRUD method in to perform save,update,delete and search operations on Employee entity.

Next we create the Employee controller to create the Rest API’s .We use the @RestController and the @RequestMapping annotation to specify the API URL.

We created different API’s to fetch all the employees ,save an employee, update or delete an employee or find an employee based on primary key.

Let’s test the REST api’s we just created. To start the Spring Boot Application we run the DemoApplication.

Spring application started:-

Lets add some employees using the Rest API.

In a similar way I created 4 more employees.

Lets update the first employee.

Now we fetch all the employees just created using the rest api.

Lets fetch the employee based on the employee id.

Lets delete an employee based on it.

Now, lets fetch all the employees again.As you can see the employee with id 1EMP is deleted.

So that was a basic Spring JPA tutorial .Happy coding:-)

Spring Basics in Java

Java offers a final class java.lang.String which represents a sequence of characters as a 16 bit unicode. The string class offer various methods that can perform various operation on strings.

Creating strings in Java

There are three ways to create strings in Java

  • Using the new operator: String str = new String(“Hello World”); When we use the new operator every time a new string is created at runtime even if the same literal exists in the pool.
  • Using String Literals: String str = “Hello World”; When you use this approach to create a string, if the object still exists in memory that is the String Constant Pool ,it does not create a new object (string) rather it gives the reference to the existing object in memory.
  • Using two or more literals together: String str = “Hello” + “World”; or equivalently String str = new String(“Hello”+”World”); This will create a new object in memory even if the object still exists in the String constant pool.

What is String Constant Pool?

String constant pool is an area in heap memory where java stores literal string values.Heap is a memory area in Java which is used for dynamic memory allocation for Java and JRE classes at runtime.New objects are created in heap memory and references to this object are stored in stack memory.These objects have global access and can be accessed from anywhere in the application.

Immutability of Strings

Strings created by the String class are immutable that means once they are created ,you can not change them.However , you can change the reference variable that refers to a String, which can make it refer to another string.

When we concatenate two string , a new string is created in memory and the old string exists in the memory.

String str1= “Dog”;

String str2 = “Cat” ;

String str3 = Str1.concat(str2);

In the above example 3 strings are created in memory. The first String “Dog”, the second string “Cat” and the third string “DogCat” because strings are immutable.

String Example

In the above example 3 objects will be created , s1 and s2 will refer to “My String Class” and two other objects will be created “MY STRING CLASS” and “my string class”

Output

s1 and s2 still refers to the “My String Class” the two new objects created ,the upper case string and the lower case string does not have a reference.

Methods in String Class

There are several methods in String class to handle/modify Strings in an application.We can use these methods to perform operations on a string.Some of these operations are:

  • Concatenating a string to another : String concat(String str)
  • Comparing String:- int compareTo(String str)
  • Extracting a substring from a string: String substring(int beginIndex)
  • Create a copy of the string with all lowercase characters: String toLowerCase()
  • Create a copy of the string with all uppercase characters: String toUpperCase()
  • Search for a character or substring in java: int indexOf(int ch)

There are many other methods in String class to perform various operations on strings.You can read about them in details at Oracle Spring Docs

Dependency Injection

Dependency Injection is a design pattern used to implement IoC. Dependency Injection separates the creation of a client’s dependencies from the client behaviour , which allows program design to be loosely coupled and to follow the dependency inversion and single responsibility principles.

  • Dependency injection involves four rules:-
  • The service objects(s) to be used.
  • The client object that is depending on the service(s) it uses.
  • The interfaces that define how the client may use the services.
  • The injector , which is responsible for constructing the services and injecting them into the client.

Any object that may be used can be considered a service. Any objects that uses other objects can be considered a client.

The interfaces are the types of client expects its dependencies to be. They may truly be interface types implemented by the services but also may be abstract classes or even the concrete services themselves.

The client should have no concrete knowledge of the specific implementation of its dependencies.It should only know the interface’s name and API. As a result , the client do not need to change even if what is behind the interface changes.However if the interface is refactored from being a class to an interface type or vice versa , the client needs to be recompiled.This is significant if the client and services are published separately. This unfortunate coupling is one that dependency injection cannot resolve.

The injector injects the service into the client.An injector may connect together a very complex object graph by treating an object like a client and later as a service for a client.

Example(Without Dependency Injection)

I will be providing a simple example of a English Language class.

We have a English Language class which is used by another class to print English Sentences.

This class is referenced by our InternationalLanguage class.

The EnglishLanguage class is referred and initialized in our InternationalLanguage class . Here’s our main class:-

Here’s the output when we run this class:-

At first look everything looks good.But our design is not flexible enough to incorporate more language class.For example if we want to add a french language class then we will need to create a new class and modify our InternationalLanguages class to refer to the FrenchLanguage class.

The EnglishLanguage class is tightly coupled with the InternationalLanguages class.We should be able to add a new Language class without making any changes in our InternationalLanguages class.That’s why dependency injection is required.

Example(With Dependency Injection)

We create a new interface called Language.

We create two classes ,one for English Language and another for French Language and implement the above interface.

And we refer the interface in our class (WorldLanguage.java) .Here we are using constructor injection to inject the required dependency(service) in the WorldLanguage class.

Here’s our main class:-

Output:-

If we want to add any other language , we just need to create another class which implements the Language class and no changes will be required in the WorldLanguage class. The interface is referred in the class and the specific class is passed to the WorldLanguage class at run time rather than compile time.

There are three ways to inject the service in your client class:-

Constructor Injection:- The dependency is injected through the client’s constructor.This is the one which we used in our example.

Setter Injection:- The client exposes a setter method that the injector uses to inject the dependency.

Interface Injection:- The dependency interface provides an injector method that will inject the dependency into any client passed into it.Client must implement an interface that exposes a setter method that accepts the dependency.

That’s all about Dependency Injection .Happy Coding everyone 🙂