Showing posts with label Spring Boot. Show all posts
Showing posts with label Spring Boot. Show all posts

Monday, September 7, 2026

Understanding & Fixing org.hibernate.LazyInitializationException in Java & Spring

I have faced this issue during my project development when I was trying to fix few testing issue. As per the scenario a one-to-many relation from VoiceServiceFileUpload class to VoiceServiceRequest class. When I want to load the VoiceServiceRequests that belongs to a voiceServiceFileUpload , I got this error. 

It seems that the error is caused by Hibernate lazily loading the VoiceServiceRequest  collection i.e. it returns a list of VoiceServiceRequest Id's only to the view. When the view tries to display the data, the session has been closed and hence, the error. Because , by default the FetchType is lazy true. After subsequent investigation and debug , I fix this by using below possible ways.


Error Log :-

ERROR, a7e3d058-4b9a-494a-87a4-08718d397b09: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: au.com.biz.service.sdp.bizservice.vmprovision.scheduler.domain.model.VoiceServiceFileUpload.VoiceServiceRequests, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: au.com.biz.service.sdp.bizservice.vmprovision.scheduler.domain.model.VoiceServiceFileUpload.VoiceServiceRequests, no session or session was closed
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
        at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
        at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
        at org.hibernate.collection.PersistentSet.hashCode(PersistentSet.java:411)
        at java.util.HashMap.getEntry(HashMap.java:424)
        at java.util.HashMap.containsKey(HashMap.java:415)
        at java.util.HashSet.contains(HashSet.java:184)
        at org.apache.commons.lang.builder.ToStringStyle.isRegistered(ToStringStyle.java:137)
        at org.apache.commons.lang.builder.ToStringStyle.appendInternal(ToStringStyle.java:421)
        at org.apache.commons.lang.builder.ToStringStyle.append(ToStringStyle.java:395)
        at org.apache.commons.lang.builder.ToStringBuilder.append(ToStringBuilder.java:840)
        at au.com.biz.service.sdp.bizservice.vmprovision.scheduler.domain.model.VoiceServiceFileUpload.toString(VoiceServiceFileUpload.java:68)
        at java.lang.String.valueOf(String.java:2826)
        at java.lang.StringBuffer.append(StringBuffer.java:219)
        at org.apache.commons.lang.builder.ToStringStyle.appendDetail(ToStringStyle.java:545)
        at org.apache.commons.lang.builder.ToStringStyle.appendInternal(ToStringStyle.java:509)
        at org.apache.commons.lang.builder.ToStringStyle.append(ToStringStyle.java:395)
        at org.apache.commons.lang.builder.ToStringBuilder.append(ToStringBuilder.java:840)
        at au.com.biz.service.sdp.bizservice.vmprovision.scheduler.domain.model.VoiceServiceRequest.toString(VoiceServiceRequest.java:106)
        at au.com.biz.service.sdp.bizservice.vmprovision.scheduler.domain.dao.hibernate.HibernateVoiceServiceRequestDao.update(HibernateVoiceServiceRequestDao.java:113)
        at au.com.biz.service.sdp.bizservice.vmprovision.scheduler.facade.spring.SpringVoiceServiceBatchJobFacade.updateRequestProvisionSendDate(SpringVoiceServiceBatchJobFacade.java:180)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
        at com.sun.proxy.$Proxy548.updateRequestProvisionSendDate(Unknown Source)
        at au.com.biz.service.sdp.infraservice.scheduler.application.job.VMProvisionBatchJob.executeJob(VMProvisionBatchJob.java:183)
        at au.com.biz.service.core.scheduler.SchedulerJob.executeTrigger(SchedulerJob.java:129)
        at au.com.biz.service.core.scheduler.SchedulerJob.execute(SchedulerJob.java:76)
        at org.quartz.core.JobRunShell.run(JobRunShell.java:203)
        at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:520)


Below the sample configuration for the entity.There is the context configuration , which is missing in this post.The configuration is configured as lazy loading true.


VoiceServiceFileUpload Entity :-

package javadevelopersguide.lab;
import java.util.HashSet;import java.util.Set;
import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.OneToMany;import javax.persistence.Table;
@Entity@Table(name="voiceservicefileupload")public class VoiceServiceFileUpload{
@Id @Column(name="FILE_ID") private int FILE_ID; @Column(name="fileName") private String fileName; @OneToMany(cascade = CascadeType.ALL, mappedBy = "voiceServiceFileUpload") private Set<VoiceServiceRequest> VoiceServiceRequests= new HashSet<VoiceServiceRequest>(0); /** * Setter and Getter Method below */}

VoiceServiceRequest Entity :-

package jdevelopersguide.lab;
import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;import javax.persistence.Table;

@Entity@Table(name="voiceservicerequest")public class VoiceServiceRequest{
@Id @Column private int ID; @Column(name="serivcename") private String serviceName; @ManyToOne(fetch = FetchType.EAGER, optional = true) @JoinColumn(name = "FILE_ID", nullable = true) private VoiceServiceFileUpload voiceServiceFileUpload; /** * Setter and Getter Method below */
}

Option 1 -

You can use OpenEntityManagerInViewFilter to open your session in view mode. So, you need to configure this in your web.xml file. But, I didn't do this :) . Because I had few more limitation as per my project structure and architecture. 

Add the below code snippet into your web.xml
----------------------------------------------------------

<filter><filter-name>OpenEntityManagerInViewFilter</filter-name><filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class></filter><filter-mapping><filter-name>OpenEntityManagerInViewFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>


Option 2 -

This issue is happening the ,because the session has closed before you load the collection.So, you can open a new session, but its not suggested.So, I didn't do this :)

After google almost few articles , I found you can also try @Transactional for that method.Because,it makes your session active. But, I didn't try this. But , you can try your luck :)



Option 3 -

Finally , I have configured the VoiceServiceFileUpload to load eager (i.e fetch = FetchType.EAGER) and it resolved my issue.

Working fix :-

@OneToMany(cascade = CascadeType.ALL, mappedBy = "voiceServiceFileUpload",fetch = FetchType.EAGER) private Set<VoiceServiceRequest> VoiceServiceRequests= new HashSet<VoiceServiceRequest>(0);


Friday, September 4, 2026

Top 10 Spring Boot Interview Questions and Answers

In this post, we will discuss some top 10 interview questions in spring boot. These questions are tricky and trending now-a-days job market. These interview questions might suitable for 0 to 8 years of experience.

1)  What is @SpringBootApplication does internally ?

Ans :- As per spring boot doc,  @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes. Spring boot enable the developer to use single annotation instead of using multiple. But, as we know spring provided loosely coupled features we can use each individual annotation as per our project needs.


2)  How to exclude any package without using the basePackages filter?

Ans:- Spring Boot allows you to exclude specific auto-configuration classes using the exclude attribute of @SpringBootApplication.

For example:

@SpringBootApplication(
    exclude = {DataSourceAutoConfiguration.class}
)
public class FooApplication {
}

You can also use excludeName when specifying the fully qualified class name:

@SpringBootApplication(
    excludeName = {
        "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"
    }
)
public class FooApplication {
}

The important point is that these options are used to exclude auto-configuration classes, not arbitrary application packages.



3)  How to disable a specific auto-configuration class?

Ans :-  You can use "exclude" attribute of @EnableAutoConfiguration. If you find that specific auto-configuration classes that you do not want 
are being applied. 

//By using "exclude"
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

On the other way , if the class is not on the class path, you can use the "excludeName" attribute of the annotation and specify the fully qualified name instead.

//By using "excludeName"
@EnableAutoConfiguration(excludeName={Foo.class})

Also spring boot provides the facility to control the list of auto-configuration classes to exclude by using the spring.autoconfigure.exclude property. You can add into the application.properties. You can add multiple classes with comma separated.

//By using property 
filespring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

 
4)  What is Spring Actuator? What are its advantages?

Ans :-  This is one of the most common interview question in spring boot. As per spring doc definition, "an actuator is a manufacturing term that refers to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change". 

As we know spring boot provides lots of auto-configuration features which helps the developer to develop ready for production components quickly.But, if you think what about the debugging , how to debug if something goes wrong. As a developer we always need analyze the logs and dig the data flow of our application to check whats going on. So, spring actuator provides a easy access to all those kind of features. It provides many features i.e. what are the beans created, what are the mapping in controller, what is the CPU usage, etc.Automatically auditing, health, and metrics gathering can be applied to your application.

It provides very easy way to access with few production ready REST endpoints to fetch all these kind of information from web. By, using these endpoints you do many things see here the endpoint docs. Nothing to worry about security, if Spring Security is present then these endpoints are secured by default using Spring Security’s content-negotiation strategy. Else , we can configure custom security by the help of RequestMatcher.

5)  How to enable/disable the Actuator ? 

Ans :-  Enabling/Disabling the actuator is easy, the simplest way to enable the features is to add  the dependency to the spring-boot-starter-actuator i.e. Starter. If you don't want the actuator to be enable, then don't add the dependency.

Maven dependency - 
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

Gradle dependency-

dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
}

6)  What is Spring Initializer?

Ans :-  This may not be a difficult question , but the interviewer always checks the subject knowledge of the candidate. Its quite often that you can't expect questions that you have prepared :). However, this is very common question asked frequently in near time.

Spring initializer is a web application , which generates spring boot project with just what you need to start quickly.As always we need a good skeleton of the project, it help you to create a project structure/skeleton properly. Initializer here.

7)  What is shutdown in actuator? 

Ans :-  Shutdown is an endpoint which allows the application to be gracefully shutdown. This feature is not enabled by default.You can enable this by using management.endpoint.shutdown.enabled=true in your application.properties file. But, be careful about this if you are using this.

8)  Is this possible to change the port of Embedded Tomcat server in Spring boot?

Ans :-  Yes, its possible to change the port. You can use the application.properties file to change the port. you need to mention "server.port" (i.e. server.port=8081). Make sure you have application.properties in your project class path, rest spring framework will take care. If you mention server.port=0 , then it will automatically assign any available port.

9)  Can we override or replace the Embedded Tomcat server in spring boot ?

Ans :-  Yes, we can replace the embedded tomcat with any other servers by using the Starter dependencies.

You can use spring-boot-starter-jetty or spring-boot-starter-undertow as dependency as per your project need.

10)  Can we disable the default web server in the spring boot application?

Ans :-  The major strong point in spring is to provide flexibility to build your application loosely coupled. Spring provides features to disable the web server in a quick configuration. 

Yes, we can use the application.properties to configure the web application type i.e. spring.main.web-application-type=none

Tuesday, June 25, 2019

Deploying Spring Boot Microservice to Docker - A Quick Guide

In this article we will deploy our spring boot micro service into docker. In our previous article we had created a simple "Hello World" spring boot micro service. Now, we will deploy that application into Docker. Check how to create a spring boot micro service

Docker with spring boot is the current popular technology stack which enables organization to seamlessly develop and make production ready artifacts. If you want to learn more about docker, read more here. 


Before deploying the application into docker,  make sure you have installed the docker. In this example we have used Docker Community Edition ( Docker CE) on windows OS. How to install docker on Windows/MacOS/Linux. We can also use Alpine Linux image , it provide minimal Linux environment to deploy & run the application.There are few docker commands to manage your application. Below sample command and screen shot shows to check the version of your installed docker engine. 

Command - 
     docker --version


What we need to deploy a spring boot application in Docker? 
  • First, we need to create an Image file for our application. Docker image is a most important component for docker engine. Docker provides a docker hub, its an library and community for container images. We can use docker hub to get the most common images .  In the below project structure , we have created a "Dockerfile.txt". If you put this docker file into the class path, then docker engine will automatically identify and load this file. This docker file name is very sensitive, so you must follow the naming convention as mentioned in the below screen shot. Docker reads commands/instructions from "Dockerfile.txt" and build the image. 

The below docker file contains the commands to create the image. Actually there are many commands used for different purpose. Here we have used few commands as per our needs.




    • FROM  - Must be the first non-comment instruction in the Dockerfile. This command creates layer from the docker image. In our case we have used java:8, It means this application will run on java 8.
    • EXPOSE - Exposing port for the endpoint. In this example we have configure 8080.
    • ADD - This command helps to takes a source and destination. Normally source is your local copy. COPY command also does same thing , but there is small difference between COPY & ADD command.
    • ENTRYPOINT - Its similar to CMD, where our command/jar file will be executed.
    • There are many other commands for creating docker image. Read more about docker command.



  • Now , run the command to build the image and deploy into docker. Before running the docker command we need to create the .jar file. Because, we are creating a jar file and then creating the jar file as docker image. So, here we have used mvn clean install command to create the jar file.

Creating a jar file. Below maven command is used to create the jar file.
     clean install 



Now , we can see below the .jar file has been created.


Create a docker image file. Below command is used to create the image file.

Syntax - docker build -t <image file name> <destination directory>

docker build -t sample-hello-microservice-springboot .
 


As per the above screenshot, it seems we have created the docker image successfully. You can check the created image by using command "docker images".

docker images




Now, our image file is ready. We can push this image to docker container using below command .

Syntax - docker run -p <exposed port> -t <image file name>

docker run -p 8080:8080 -t sample-hello-microservice-springboot



Now our micro service has been deployed to docker and its exposed on port 8080 as per our configuration in the docker file. We can check the running container and its status.


Now we can also accessed from browser as below.

There are few useful docker command as below .

docker system prune 

This will remove:                                                                                                                               - all stopped containers
       - all networks not used by at least one container
       - all dangling images     
       - all dangling build cache 

docker ps -a 

This will show all process in docker engine.

docker images

This will show all the images you created.

docker stop <container id>

This will stop the container.

If required , there are help options to get the help about each command. Read more.
docker ps --help
docker run --help


Hope it will help you.


Monday, June 17, 2019

Spring Boot JAR Error: No Main Manifest Attribute

The error "no main manifest attribute, in sample-hello-microservice-springboot.jar" occurred while trying to execute the JAR file.

This was an unusual issue with JAR file execution. In this case, I was trying to run the Docker image. The reason for this issue was that, during JAR execution, it was not able to locate the main class.

Below is the main class, HelloApplication, and the pom.xml file. It seems that the Spring Boot Maven plugin was missing, along with the configuration for the manifest (mainClass).

HelloApplication.java

package com.techbyteslearn.lab.springboot.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }
}

pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>sample-hello-microservice-springboot</groupId> <artifactId>sample-hello-microservice-springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <description>Sample Hello microservice with Spring Boot.</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <!-- Setup Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- Setup Spring MVC & REST with Embedded Tomcat --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <archive> <manifest> <mainClass> com.techbyteslearn.lab.springboot.application.HelloApplication </mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> </project>

Solution:

I added the Spring Boot Maven plugin and configured the main class in the pom.xml file.

After making this change, the JAR was created with the required manifest information, and the application started working fine when the JAR was executed.

You can see the screenshot below to see the result.






Checking on browser.












Hope this will help you. 

Thursday, March 15, 2018

How to Create Your First Spring Boot Application

Developing your first Spring Boot application is quite easy. As we know Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". Its basically to minimize the configuration. 

In this example I have used below frameworks and tools for this example.

1. Maven 3.3.9 
2. JDK 1.8
3. Eclipse IDE
4. spring-boot dependency 



First step - In eclipse create a maven project  "hello-world-spring-boot" as below .


Then add the dependency for spring-boot and plug-in in the pom.xml file.


Pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javadevelopersguide.www</groupId>
<artifactId>hello-world-spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<description>This is a hello world example with Spring Boot.</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

</plugins>
</build>
</project>
Then create a controller class "HelloWorldController" with a rest api method sayHello()

HelloWorldController.java
package com.techbyteslearn.springboot.example;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class HelloWorldController {
@RequestMapping("/hello")
@ResponseBody
public String sayHello() {
return "Hello World Developer!!!";
}
}
I have use below annotations in my controller. Here in this example the uri path is /hello

@Controller - This is used to specify the controller , as its spring framework basic.
@EnableAutoConfiguration - This enable auto configuration for Application Context. 
@RequestMapping - This is used to map to spring mvc controller method.
@ResponseBody - Used to bind http response body with a domain object in return type.Its behind the scenes. 

Now , my controller is ready.Just I need a luncher , who can lunch my spring boot application. I have created a "SpringBootApplicationLuncher".

SpringBootApplicationLuncher.java


package com.techbyteslearn.springboot.example;
import org.springframework.boot.SpringApplication;

public class SpringBootApplicationLuncher {
public static void main(String[] args) {
SpringApplication.run(HelloWorldController.class, args);
}
}

Now you can run this launcher to start the spring boot application.Then, you can see the below screenshot showing the tomcat is started. As you know spring-boot is embedded with tomcat feature.



Now , your application is up and running . I have highlighted above that the tomcat is started on default port 8080

Try this tomcat URL, which is running now :- http://localhost:8080/hello




Alternatively , Also you can also start your spring-boot application on command line (Terminal). I have used windows OS.

You can use the below Maven Command  to build and run this spring-boot application :- 


1. Build the application :- mvn clean install



2. Run the application :- mvn spring-boot:run




 Now the service is running on tomcat port 8080 .Use the below URL to access the sayHello() api.

http://localhost:8080/hello