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 🙂

Log4j2 Maven Configuration

This post is regarding logging (log4j2) configuration in a maven project.

Here’s the steps to add lo4j2 in your maven project :-

Maven Project Structure

You need to have the above project structure .The log4j2.xml that is the logging configuration file ,needs to be placed under src/main/resources folder.

Dependencies

The following dependencies to be added for logging configuration.

Log4j Dependencies
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.2</version>
</dependency>
Jackson Dependencies

You also need to add the jackson dependencies.If you don’t add these dependencies you will getting the following error while running your application.Log4j require these dependencies.

Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.ser.FilterProvider
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
… 21 more

Log4j XML Configuration

You need to create log4j configuration file and place it under src/main/resources .

Rolling File Appender

I have created two Rolling File appenders

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="TRACE" name="web" monitorInterval="30" >
<Appenders>
<RollingFile name="RollingFile" fileName="/Users/ensiahusain/var/log/httpd/log4jexample/log4jexample.log"
filePattern="/Users/ensiahusain/var/log/httpd/log4jexample/log4jexample-%d{yyyy-MM-dd}-%i.log">
<PatternLayout>
<Pattern>%d{ISO8601},%-5p\ [%c],[%X],%m,%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="1 MB"/>
</Policies>
</RollingFile>
<RollingFile name="AuditLogAppender" fileName="/Users/ensiahusain/var/log/httpd/log4jexample/log4jexample.log"
filePattern="/Users/ensiahusain/var/log/httpd/log4jexample/log4jexample-%d{yyyy-MM-dd}-%i.log">
<JsonLayout locationInfo="true" complete="false" charset="UTF-8" compact="true" eventEol="true" properties="true"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="1 MB"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="RollingFile"/>
</Root>
<Logger name="AuditLogger" level="INFO" additivity="false">
<AppenderRef ref="AuditLogAppender"/>
</Logger>
</Loggers>
</Configuration>

Running the Java Application

Create a java application and create a logger instance and try to add some logs for testing the logging configuration.

After you run this java application logs should be created at the file location given in the log4j xml file.

Logging File

That’s all about log4j2 configuration.Happy Coding 🙂

ORA-01882: timezone region not found error in Payara Server

This tutorial will explain how to resolve the “time zone region not found error ” when the user tries to set a JDBC Connection pool in payara server.

We usually get this error when we try to create a JDBC Connection pool in payara server.You will get the following error when you try to ping a newly created connection pool.

The error message shows ORA-01882 : timezone region not found.

To fix this error go to server-config under Configurations. Go to JVM Options( server-config->JVM Settings->JVM Options).

Add the following JVM option and save it:-

-Doracle.jdbc.timezoneAsRegion=false

JVM Options Payara server (timezone Region)

Then try to ping the JBC connection pool and it should work fine.

JDBC Connection Pool in Payara Server

The payara server version which I used is 4.1.1.154. But this solution should work on all the versions of payara server.

Let me know if it works for you. Happy Coding 🙂