Wednesday, January 29, 2020

How to setup Google Cloud Compute Engine for Spring Boot project?

You should have the Google account to for this. You will get $300 credit for 12 months for Google Cloud computing. In this article there are 2 parts. 1st will will tell you the billing part information and 2nd it will explain how to setup the project. So let's follow some steps to achieve this goal.

PART 1 : Setup Billing Information

Step 1: Search Google Cloud in Google or directly go to https://cloud.google.com/ . You need to setup the Cloud Platform. Click on Continue.
How to setup Google Cloud Compute Engine for Spring Boot project?

Step 2: Fill the required form.
javaaltaf How to setup Google Cloud Compute Engine for Spring Boot project?

It will also ask for the payment details.
card details google cloud compute engine
Here Payment method is required. You need to give your debit/credit card details. You need to pay 1 Rupee to the GOOGLE CLOUD INDIA. Now click on START MY FREE TRIAL. After completion this you will get this info.
transaction completion compute engine

Step 3: Next step is to verify the your payment details. Whether you are the payment owner or not.
payment verification google cloud compute engine
For verification, they will ask your first/last name and need to upload one government id proof and debit/credit photo. It might take some hours for verification. After verifying you will get information like this.
payment verification completion google cloud compute engine
After completing the verification, you will get free access for 1 year. Now you can perform the required task for google cloud computing.



PART 2: Setup the execution environment

Step 1: Open Google Cloud Console and go to Compute Engine -> VM Instances

google cloud compute engine vm instance


Now Create an instance and configure your machine. Based on your Machine Type, they will charge you money. Here you can configure your Operating System, Hard Disk size etc.
machine setup google cloud compute engine

After creating VM Instance, your machine will be visible with ip address.
machine info google cloud compute engine
Step 2: Connect your machine by clicking on SSH or by clicking drop down menu Open in browser window. It will open in new window. You will see the black screen with username & machine name. This is your machine terminal. Any operation if you want perform, you can do only with this terminal.
google cloud compute engine terminal

You can open this terminal from your local terminal/command prompt but before you need to set your public ssh key into metadata of Google Cloud. To set this open Compute Engine -> Metadata
google cloud compute engine metadata
To generate ssh key, open your local terminal and type
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" 
It will ask Enter file in which to save the key:. You can type the file name on which you want to save. If you want default file name(id_rsa) then just press Enter.
Again it will ask Enter passphrase (empty for no passphrase):. You can use password or if you don't want then just hit Enter 2 times. File will be saved into /home/username/.ssh/filename.pub. Go to the Home location and press Ctrl+H to see the hidden files. .ssh directory will be hidden. Go to inside the ssh directory and open the file id_rsa.pub with any of your favorite editor and copy the complete text and paste into Metadata SSH Keys. Click on Edit
google cloud compute engine metadata ssh keys
then Click on Add Item
google cloud compute engine metadata ssh keys
Now here paste your copied ssh key then Save
google cloud compute engine metadata ssh key add item
Finally, open your local terminal and connect with your host machine ip address. 
ssh username@34.93.xxx.xxx
First time it will ask yes/no question. press yes and hit Enter. Congrats! you have connected. Now you need to install the required software like Java, Git, Maven  etc.
Install Java : sudo apt-get install openjdk-8-jdk
Git : sudo apt-get install git
Maven : sudo apt install maven
Curl : sudo apt install curl
Nano(Editor) : sudo apt-get install nano
Now you will have to install PM2 which is a process manager for the JavaScript runtime Node.js. I know you have a question What is the need of Node in Java environment? You have good question which will be answered below.

Step 3: Clone an Spring Boot project from your Github repository. If you don't have you can clone from my Github repository. Now execute your project. But how? You can execute by using maven command.
mvn spring-boot:run
Great, you have deployed your Spring Boot application into Google Cloud Compute Engine but what will happen if you close your terminal? :) :) :)
Oh no! my application stopped working.

Yes, this is the problem. You can solve this problem by executing the command in background.
setsid mvn spring-boot:run
Now even you close the terminal, your application will work but what will happen if you need to restart the server? You will get this error
Web server failed to start. Port 8080 was already in use.
mvn spring-boot:run termnal gcp compute engine
You can solve this problem as well. What you need to do is
A. First of all, you need to find the pid(process id) of the running application based on the port.
lsof -i:8080
You will get output as
lsof -i:8080
2965 is your processId.

B. Then you need to kill the process by using this command.
kill -9 2965
C. And again you need to start the server by using setsid command.

Now you can think how this is painful. Hence to resolve this issue you can use PM2.
curl -sL https://deb.nodesource.com/setup_10.x -o nodesource_setup.sh
sudo bash nodesource_setup.sh
sudo apt-get install nodejs
sudo npm install -g pm2

Step 4: I think you have already cloned the project from Github. Then go to the project directory by using cd command
git clone https://github.com/altafjava/spring-boot-test.git
cd spring-boot-test/
You will have to create one .sh file which will be used by the PM2 to restart the server. In your .sh file you need to write the command which is used to execute the spring boot project that is nothing but mvn spring-boot:run
echo "mvn spring-boot:run">server.sh
chmod +x server.sh
Finally, restart the server
pm2 start server.sh
You can even check the logs on runtime by using
pm2 logs

If you have come so far, then I think you have done great job. Congrats!
Still you have any doubt feel free to comment.

Tuesday, January 28, 2020

How to deploy Spring Boot app in Google Cloud Compute Engine with embedded tomcat?

Now a days deploying Spring Boot application is quite easy in Cloud Platform. A lot of articles already have published on the web but unfortunately I have not seen a single article written in this topic. Hence I planned to write a blog in this topic. You will get a lot of article on deployment of Spring Boot application in Google Cloud App Engine but not on Compute Engine. Hence be ready for Compute Engine.

How to deploy Spring Boot app in Google Cloud Compute Engine with embedded tomcat?


First Let's understand the difference between App Engine & Compute Engine.
App Engine is a Platform-as-a-Service. It means that you simply deploy your code, and the platform does everything else for you. For example, if your app becomes very successful, App Engine will automatically create more instances to handle the increased volume.

Compute Engine is an Infrastructure-as-a-Service. You have to create and configure your own virtual machine instances. It gives you more flexibility and generally costs much less than App Engine. The drawback is that you have to manage your app and virtual machines yourself.

I will recommend to use Ubuntu operating system if you are using Compute Engine and install the required software like Java, Git, Maven etc. You can visit here to know How to setup Google Cloud Compute Engine for Spring Boot project?  Let's come to our main topic.


Open the server terminal by going to Compute Engine -> VM Instances -> SSH or you can open from local terminal as well if you have configured your ssh key in your machine. To open/connect locally use this command.
ssh username@34.93.xxx.xxx
First time it will ask yes/no question. press yes and hit Enter. Congrats! you have connected. Now you need to install the required software like Java, Git, Maven  etc.
Install Java : sudo apt-get install openjdk-8-jdk
Git : sudo apt-get install git
Maven : sudo apt install maven
Curl : sudo apt install curl
Nano(Editor) : sudo apt-get install nano
Now you will have to install PM2 which is a process manager for the JavaScript runtime Node.js. I know you have a question What is the need of Node in Java environment? You have good question which will be answered below.

Clone an Spring Boot project from your Github repository. If you don't have you can clone from my Github repository. Now execute your project. But how? You can execute by using maven command.
mvn spring-boot:run
Great, you have deployed your Spring Boot application into Google Cloud Compute Engine but what will happen if you close your terminal? :) :) :)
Oh no! my application stopped working.

Yes, this is the problem. You can solve this problem by executing the command in background.
setsid mvn spring-boot:run
Now even you close the terminal, your application will work but what will happen if you need to restart the server? You will get this error
Web server failed to start. Port 8080 was already in use.
mvn spring-boot:run termnal gcp compute engine
You can solve this problem as well. What you need to do is
1. First of all, you need to find the pid(process id) of the running application based on the port.
lsof -i:8080
You will get output as
lsof -i:8080
2965 is your processId.

2. Then you need to kill the process by using this command.
kill -9 2965
3. And again you need to start the server by using setsid command.

Now you can think how this is painful. Hence to resolve this issue you can use PM2.
curl -sL https://deb.nodesource.com/setup_10.x -o nodesource_setup.sh
sudo bash nodesource_setup.sh
sudo apt-get install nodejs
sudo npm install -g pm2
I think you have already cloned the project from Github. Then go to the project directory by using cd command
git clone https://github.com/altafjava/spring-boot-test.git
cd spring-boot-test/
You will have to create one .sh file which will be used by the PM2 to restart the server. In your .sh file you need to write the command which is used to execute the spring boot project that is nothing but mvn spring-boot:run
echo "mvn spring-boot:run">server.sh
chmod +x server.sh
Finally, restart the server
pm2 start server.sh
You can even check the logs on runtime by using
pm2 logs

If you have come so far, then I think you have done great job. Congrats!
Still you have any doubt feel free to comment.

Sunday, January 26, 2020

[Solved] no tests found with test runner junit 5

We often get this error in Eclipse/STS while working with JUnit. As we know JUnit has released JUnit5 after successor of JUnit4. When we create Spring Boot starter project whose version is higher than 2.1.4.RELEASE then by default Spring adds the JUnit5 dependencies.

no tests found with test runner junit 5

It can have multiple solutions but as of now I am explaining one of the solution here. So you have to follow some steps. In a simple way this blog will tell you to use JUnit4 instead of Junit5 but later I will update for JUnit5 as well.


Step 1:
If you are using Spring Boot then by default Spring adds spring-boot-starter-test dependency like this.
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 <scope>test</scope>
 <exclusions>
  <exclusion>
   <groupId>org.junit.vintage</groupId>
   <artifactId>junit-vintage-engine</artifactId>
  </exclusion>
 </exclusions>
</dependency>
Here you need to remove or make comment the <exclusions>. Now if you will check in the Maven Dependency you will get JUnit4.
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 <scope>test</scope>
</dependency>

Step 2:
Goto the the package src/test/java and open one of the JUnit test class. You need to change then @Test annotation import from import org.junit.jupiter.api.Test; to import org.junit.Test;


Step 3:
Now open your one of the JUnit test class then right click. Then goto Run As -> Run Configurations. Now Inside the Test tab, there is an option Test runner. Change it to JUnit5 to JUnit4 then click on Run.

Run Configurations

Congrats! Now it will run your JUnit test. Feel free to comment or give feedback if required any modification.

Wednesday, January 22, 2020

How to install free ssl certificate in spring boot using Let's Encrypt


As we know ssl provides the extra layer of security. Every packet transferred between client and server is encrypted using public or private key cryptography. Now a days everyone ensuring to protect their web application through ssl certificate. If you have developed your web application by using Spring then you are at right place. Here you will learn how to install ssl certificate without paying anything.

How to use install free genuine ssl certificate in spring boot application using let's encrypt


There are multiple ways to generate ssl certificates. Even Java also has provided a tool(keytool). If you will use keytool then you can enable https but still you will see Not Secure in the browser URL like this.

Not Secure


Hence we are here to make this as secure with green color https URL. To make this green https, we will use Let's Encrypt. Let's Encrypt is a non-profit certificate authority run by Internet Security Research Group that provides X.509 certificates for Transport Layer Security encryption at no charge. So Let's follow the steps.

Step 1:
Stop the application or server running on the port 80 or 443. You can check whether any application or server running or not on a particular port by using lsof command.
lsof -i :8080

To stop the application or server, you can use kill command.
kill -9 pid

Step 2:
You need to install the certbot on your server. You can open the server terminal by using ssh command.
ssh alt@xxx.xxx.xxx.xxx
where xxx is your server ip address. Now use this command to install certbot if you have Ubuntu operating system.
sudo apt-get update -y && sudo apt-get upgrade -y
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install python-certbot-apache

Step 3:
Now generate the ssl certificate by using the following command.
certbot certonly -a standalone -d api.example.com
where api.example.com is your domain name. This will generate the 4 .pem files inside etc/letsencrypt/live/api.example.com-0001/.
To goto this directory, use this command.
cd /
cd etc/letsencrypt/live/api.example.com-0001/
To see the files in the current directory use the ls command.
ls
This will show the following files list.
cert.pem  chain.pem  fullchain.pem  privkey.pem  README

Step 4:
As we know Spring supports .p12 file for ssl certification. Hence we need to convert the .pem files into .p12 file. To generate PKCS12 file from PEM files we shall have to use openssl command.
openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out api_example_com.p12 -name myalias -CAfile chain.pem -caname root
Hint:
-out will the converted file name
-name will be your alias name

This will ask to enter password. After entering the password, again it will ask the password. You will have to enter the password 2 times.

Step 5:
Finally, it will generate the api_example_com.p12 file in the current directory. Now you need to copy this file in Spring Boot Maven project resource directory(src/main/resources/). To copy the file from server location to local machine, you can scp command but I will recommend to first copy the file to your ubuntu home location because there may be a lot of users present that OS.
cp api_example_com.p12 /home/myusername/
exit
exit
Now you are in local machine terminal. From here you need to copy the file from server machine home location to your local machine.
scp alt@xxx.xxx.xxx.xxx:api_example_com.p12 .
Hint: Here . means current directory. You can change it your appropriate directory. This will be downloaded into your home directory.

Step 6:
Now copy this(api_example_com.p12) file and paste in src/main/resources of your Spring Boot project. Now do some changes in your application.properties file
server.ssl.enabled=true
server.ssl.key-store=classpath:api_example_com.p12
server.ssl.key-store-password=mypassword
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=myalias
http.port=80
server.port=443

Step 7:
Here you need to take special care. After saving this configuration in your application.properties file, if you start the server locally, it will fail to start. Because the .p12 has mapped to your ip xxx.xxx.xxx.xxx and your current ip is 127.0.0.1 that is localhost. Hence only this will start on your server. To avoid this happening, you can use profile concept of Spring. Hence you need to create another property file ie application-prod.properties then cut and paste those ssl configuration in application-prod.properties file and remove from application.properties file.
You need to write one more line in application.properties file
spring.profiles.active=prod
Now if you want to start the server locally then comment this and start.
#spring.profiles.active=prod
It will start locally without ssl but when you want to start the server on server machine then you need to uncomment this config.

Step 8:
This is an optional step but I will recommend to do. In this step you need to write a config class
that will redirect every request that is coming via http to https.
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Profile("prod")
@Configuration
public class TomcatConfig {

@Value("${http.port}")
private int httpPort;

@Bean
public EmbeddedServletContainerFactory servletContainer() {
 TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
  @Override
  protected void postProcessContext(Context context) {
   SecurityConstraint securityConstraint = new SecurityConstraint();
   securityConstraint.setUserConstraint("CONFIDENTIAL");
   SecurityCollection collection = new SecurityCollection();
   collection.addPattern("/*");
   securityConstraint.addCollection(collection);
   context.addConstraint(securityConstraint);
  }
 };
 tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
 return tomcat;
}

 private Connector initiateHttpConnector() {
  Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
  connector.setScheme("http");
  connector.setPort(httpPort);
  connector.setSecure(false);
  connector.setRedirectPort(8443);
  return connector;
 }
}

Congrats! You are done. Feel free to comment, if you have any doubt.


Saturday, January 26, 2019

How to deploy/host the maven artifact of a project to Google Cloud Storage?

First of all, there is a big question "Why we need to host/deploy our maven artifact of a project into Google Cloud Storage"?
Answer: If some classes are common across multiple projects then we can create a jar file of these classes and we can use in both the projects by adding this jar file into classpath location. But if we are following this approach we can face multiple problems.

  1.  As we are living in the world of Apache Corporation, everyone is using a maven build tool. No one wants to use the external library in their projects. If we are external libraries then managing the dependency is really painful.
  2. If there is a change in the common classes then again we will have to package these classes into jar file then set this jar file in all the projects.


For clear understanding, let's take an example.
In a company, suppose we have 2 projects. One is for main core project and another one is for CSR(Customer Service Representative). As we know for managing our core project we need  Customer Service team. For this CSR team, we need to build an application so that they can handle the support management.
As we know nowadays sending OTP is mandatory for almost all the application for signup, login, etc. To send the OTP, we need SMS gateway. There are a lot of SMS gateway providers. You can find here and we are using one of them. Almost all they have provided an API to send the SMS through the program.
Now we have a requirement to send OTP in the main project and as well as we also require to send tracking and promotional SMS to our customers from CSR project. In this case, we need to write the program to send the SMS two times. Hence the same code will be duplicated. If there is a change in the SMS Gateway API we need to change in all the project wherever we are using that API. In this case, we can create a separate project for sending SMS and we can deploy this project into jfrog, nexus, archiva etc. Now wherever we require the SMS gateway just we need to add the GAV(groupId, artifactId, version) into our project and automatically the class which we have deployed into our remote repositories will be downloaded like other maven artifact and we don't need to manage the dependency. Everything will be taken care by maven.

Let's understand another example
In both the projects Main & CSR we are retrieving the data from Database. For this, we are using Hibernate(is an ORM Framework. Generally it converts the table data which is in RDBMS format to Java object format & vice-versa). To map the table into Java object and Java object to the table we have to write entity class. Name of the class will map to name of the table and no. of attributes of the class will map to no. of columns of the table. Hence if we want ORM support then we shall have to create same no. of attributes in the class as many columns are available in the table.
Now, we have a CUSTOMER table. For this table, we have created one Customer class. As we know we need the customer information in both the projects. Yes, we can duplicate the classes in both the projects but when if there is a change in the table structure we shall have to modify in all the project's entity classes. Not we can have only Customer class which is common.  There can be a lot of classes which is common across multiple projects. In this case, modify class structure is a very tedious job.

Hence we can create the artifact for these common classes and deploy into remote repositories so that we can use in all the project without modifying the source code.

Now the thing is
Why we should use Google Cloud Storage rather than using  jfrog, nexus, archiva?
Yes, of course, you can go with jfrog, nexus, archiva etc. But if you have hosted your application into Google Cloud Platform then obviously you will want to use other Google services. Now, in this case, we can go with Google Cloud Storage to host or deploy our artifact into GCS.

Now we shall see the complete process to deploy/host the maven artifact into GCS. This is in 2 parts. The first part is how to upload the artifact into the GCS bucket and second part is how to download and use the uploaded artifact from GCS bucket.

PART 1 : 

Step 1 :
Create a maven quickstart project. You can create through the command prompt or by using IDE.
mvn archetype:generate -DgroupId=com.javaaltaf -DartifactId=SMSGateway -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Step 2 :
Now create a simple class for testing purpose. By the way, based on your requirement you can create multiple classes.
public class MessageSender {
 public String sendSMS(String mobile, String message) {
  return "SMS sending....to " + mobile + "  with messsage=" + message;
 }
}

Step 3 :
You will have to add an extension inside <build> tag in your pom.xml provided by Emmanouil Gkatziouras.
<build>
  <extensions>
   <extension>
    <groupId>com.gkatzioura.maven.cloud</groupId>
    <artifactId>google-storage-wagon</artifactId>
    <version>1.6</version>
   </extension>
  </extensions>
</build>
You can download the latest google-storage-wagon from here. This will upload and download our artifact to/from Google Cloud Storage.

Step 4 :
Open your Google Cloud Platform. Go to Menu->Storage->Browser.

Google Cloud Storage

This will open one dashboard where you will have to create a bucket where your artifact will be stored.

Create Bucket Button

Click on Create Bucket.

Create Bucket

You can give any name to you bucket based on your requirement but the name must be unique across the cloud storage. Here I have given altafsms
After creating the bucket this will look like this

Bucket Created

Goto overview section where you will see Link URL, Link for gsutil and other additional information of your bucket. We will use gsutil URL.

Bucket Overview

Step 5 :
Now we need to set up the bucket information into pom.xml so that maven can understand the destination of the artifact. For this we shall have to add <distributionManagement> tag just after the <project> tag.
<distributionManagement>
  <snapshotRepository>
   <id>mysms-snapshot</id>
   <url>gs://altafsms/snapshot</url>
  </snapshotRepository>
  <repository>
   <id>mysms-release</id>
   <url>gs://altafsms/release</url>
  </repository>
 </distributionManagement>
Generally, a snapshot version in Maven is one that has not been released. The idea is that before a 1.0 release (or any other release) is done, there exists a 1.0-SNAPSHOT. Here <snapshotRepository> is same as snapshot version. and <respository> is released version. You can use either <snapshotRepository> or </repository> at a time. This will decide based on the version you have mentioned into your pom.xml file. If the version is SNAPSHOT then it will upload into gs://altafsms/snapshot. If it is released version then it will be uploaded into gs://altafsms/release. You can give any unique id but better to follow some convention or standard. In <url> tag you need to provide the gsutil URL which already we have created.

Step 6 :
You should have Google Cloud SDK installed in your PC. If not then please install. You can get help from here. If it is already installed you can check by using this command (gcloud info) in terminal/command prompt.
After installing this goto your project directory and open the terminal/command prompt and log in with the account that has the access to the bucket which we have created previously through gcloud.
gcloud auth application-default login
This will redirect you in a browser to allow the access of google account. If it is not redirecting to the browser then copy and paste the URL which is shown in the terminal into the browser and then login with google account. After successfull login you will see a message like Credentials saved to file: [/home/alt/.config/gcloud/application_default_credentials.json]. Until you get this message deployment will not work. If you see this message then you are allowed to access the bucket information.

Step 7 :
Now go to your project directory and open command prompt or terminal and just type this command.
mvn deploy

This command will successfully upload your artifact into your GCS bucket. This should take more than 60 seconds. You can get a message either BUILD SUCCESS or BUILD FAILURE.


PART 2 :

In this section, we shall understand how to use the artifact which is already uploaded into Google Cloud Storage Bucket. So here also we shall follow some steps.

Step 1 :
To use the artifact, first of all, we shall have to create a maven project. It can also be a Spring Boot project.

Step 2 :
Now add the same <extension> into your pom.xml which you already added in the previous project.
<build>
<build>
 <extensions>
  <extension>
   <groupId>com.gkatzioura.maven.cloud</groupId>
   <artifactId>google-storage-wagon</artifactId>
   <version>1.6</version>
  </extension>
 </extensions>
</build>
After that add the GAV(groupId, artifact id, version) of the earlier project as <dependency> tag in your pom.xml file.
<dependency>
  <groupId>com.javaaltaf</groupId>
  <artifactId>SMSGateway</artifactId>
  <version>1.0</version>
</dependency>
Note: If both the project is open in the IDE(Eclipse) then it will pick the complete project as Maven Dependencies. Hence to avoid this temporarily you can remove the earlier project or just change the artifactId so that maven could find the artifact from GCS Bucket.

Step 3 :
Now you can create a Test class to test the MessageSender class.
public class Test {
 public static void main(String[] args) {
  MessageSender messageSender = new MessageSender();
  String message = messageSender.sendSMS("9876543210", "Hello Altaf, How are you?");
  System.out.println("Returned Message = " + message);
 }
}

Output: Returned Message = SMS sending....to 9876543210  with messsage=Hello Altaf, How are you?


So, finally, we have deployed our artifact into Google Cloud Storage Bucket and used it. You can download both the projects from Github.
Project 1 : SMSGateway
Project 2 : TestSMSGateway
Hope you understood. If still any doubts you can comment here.

Saturday, January 12, 2019

How to change the table name of an Hibernate entity at run-time?


Sometimes, There are the tables that are being generated on a monthly basis but the table structure of all monthly tables are same.

Let's say we have a biometric fingerprint attendance machine for our employees and this machine is automatically storing attendance details in the database on monthly basis. Hence the table name changes every month but its column/structure remains the same.

Example:- Suppose today is 13-01-2019. Now for today's data will be stored into table ATTENDANCE_1_2019.
Similarly, our tables name will be ATTENDANCE_2_2019, ATTENDANCE_3_2019 ...... ATTENDANCE_12_2019.

But the columns of all the tables remains the same.
deviceLogId,
empId,
checkin
checkout

Now, At end of the month, we need to calculate the salary for every employee. For this, we need to read the data from these tables. For this, we are using Hibernate. As we know Hibernate is an ORM Framework. Means for a per table we need to create Entity class so that Hibernate can map the table into the entity class and vice-versa.

So, Let's create our entity class.

@Entity
@Table(name = "ATTENDANCE_1_2019")
public class Attendance {

 @Id
 private int sno;
 private int deviceLogId;
 private int employeeId;
 private Date checkin;
 private Date checkout;

//setters & getters
}

Now we will write our DAO class to fetch to fetch the data from table ATTENDANCE_1_2019. It will work fine but what happens if month comes to February?

In February month our Biometric fingerprint attendance machine stores attendance details in ATTENDANCE_2_2019 table. Then how can we fetch the data from ATTENDANCE_2_2019(February) table because our Attendance entity class is mapped with ATTENDANCE_1_2019 table?

Hence again we need to write entity class for February(ATTENDANCE_2_2019), March(ATTENDANCE_3_2019), April(ATTENDANCE_4_2019) and so on. Now the question is how many entity class you will write? In a year you need to write 12 entity class. So is it a good approach to write too many entity class even all the entity class has the same structure/attributes just because of table name?

Hence we can solve this problem by changing the Entity class name at runtime by using Hibernate Interceptor.

The Hibernate Interceptor is an interface that allows us to react to certain events within Hibernate. Interceptor Interface provides methods, which can be called at different stages to perform some required tasks like onSave(), onDelete(), onPrepareStatement() etc.
You can read more in Hibernate Documentation.


Hence we will take advantage of onPrepareStatement(String sql) method. As we Hibernate uses HQL(Hibernate Query Language) but internally these query is converted into SQL. Means at the time of generating SQL if there is any callback method where we can get the SQL and can change the table name then we can solve this problem. Hence Hibernate has provided one method called onPrepareStatement(). Before sending the query to the Database first it will call onPrepareStatement(String sql). Hence here we can change the table name by replacing the older name with the new table name.

Example:- So currently, we have the Attendance list of January & February month. We will fetch this data using Hibernate.
Attendance_1_2019


Attendance_2_2019

For this, we need to create one DAO like this
@Repository
public class AttendanceDAO {
 @Autowired
 private SessionFactory sessionFactory;

 public List getAllAttendance() {
  Session session = sessionFactory.openSession();
  Query query = session.createQuery("from Attendance");
  List attendanceList = query.list();
  return attendanceList;
 }
}
As we are using show_sql=true, we can see the query generated by the Hibernate.
Hibernate:
    select
        attendance0_.sno as sno1_0_,
        attendance0_.checkin as checkin2_0_,
        attendance0_.checkout as checkout3_0_,
        attendance0_.deviceLogId as deviceLo4_0_,
        attendance0_.empId as empId5_0_
    from
        ATTENDANCE_1_2019 attendance0_
But here the problem is, This session will always go to ATTENDANCE_1_2019 table because in entity class it is mapped to this table. Hence we need to write our custom Interceptor class like this
public class CustomInterceptor extends EmptyInterceptor {
 @Override
 public String onPrepareStatement(String sql) {
  System.err.println("Before Modifying SQL =" + sql);
  sql = sql.replace("ATTENDANCE_1_2019 ", "ATTENDANCE_2_2019 ");
  System.err.println("After Modifying SQL =" + sql);
  return sql;
 }
}
And in this class, we are modifying the existing query by replacing the table name and again we are sending this query to the HIbernate. Now Hibernate will fetch the data from ATTENDANCE_2_2019 table.

Here I have hardcoded the table name which we should not. Hence we can use the Calendar class of Java to get the current month and year. Hence we can change your CustomInterceptor like this
public class CustomInterceptor extends EmptyInterceptor {
 @Override
 public String onPrepareStatement(String sql) {
  System.err.println("Before Modifying SQL =" + sql);
  Calendar calendar = Calendar.getInstance();
  int month = calendar.get(Calendar.MONTH) + 1;
  int year = calendar.get(Calendar.YEAR);
  String tableName = "ATTENDANCE_" + month + "_" + year;
  sql = sql.replace("ATTENDANCE_1_2019 ", tableName);
  System.err.println("After Modifying SQL =" + sql);
  return sql;
 }
}


In this way, we can change the entity class table at runtime. No need to write multiple entity class. One entity class is enough.

Github Link : ChangeTableNameAtRuntime


Hope we understood. If still any doubts you can comment here.