Create DynamicJasper Report in Java SpringBoot

So, what is DynamicJasper? DynamicJasper is a superior version of JasperReports but with the added capability of the report being generated at runtime. Not to mention it is very fast, very customizable and very easy to implement.

What we’ll be covering in this article, is how to create reports using DynamicJasper at runtime in Java SpringBoot using Java Model Class as its Data Source. For the example in this article, I have already connected my JavaSpring project with MySQL database and have already created API CRUD services in it. Which is all the basic stuff. Don’t worry, I have uploaded the project on to my GitHub account and have shared the link below.

Let me show you the database and the model class with all the properties. As shown in the picture below, here is a basic employee table with just a few records and I will be populating them in the report further ahead with the employee model class as the Data Source.

MySQL Database Table and its records
MySQL Database Table and its records

There it is, a traditional employee table with the traditional columns as seen above. Next will make a Java spring boot project from Spring Initializr. Which you should be already familiar with if you’ve used SpringBoot before. I’m still going to attach a picture just to show how to set up the basic layout for creating the project. for creating the project

Springinitializr Layout for Creating a SpringBoot Project
Springinitializr Layout for Creating a SpringBoot Project

After this, you can click on generate button which will download the project open up the project in any of your favorite editors or an IDE whereas I am going to use IntelliJ IDE for this project. After opening the project, I have already made all the necessary controller services and model classes and I’ve already added the configuration for connecting it to my local MySQL Server. you can do the same cause that is all very basic if you’re having any issues, you can always download the project, I have already uploaded this project onto my GitHub profile The link for which I will be sharing is at the bottom of this article.  

So, the first thing is that we’re going to tackle an upcoming problem that we’ll face when implementing a dynamic Jasper third-party library. So, let’s open up “DynamicJasperReportApplication.java” file, and REPLACE the old code with the new one shown below: 

				
					public static void main(String[] args) {
    SpringApplicationBuilder builder = new SpringApplicationBuilder(DynamicJasperApplication.class);
    builder.headless(false);
    ConfigurableApplicationContext context = builder.run(args);
}
				
			

Before Changes

Before Changes
Before Changes

After Changes

After Changes
After Changes

OK the next step is one of the crucial ones, it’s to add the dependency in the pom.xml file. There shall be two dependencies added. One would be simple jasperreports and the other would be dynamicJasper”. So let’s open pom dot XML file and add the following dependencies: 

				
					<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>6.9.0</version>
</dependency>

<dependency>
    <groupId>ar.com.fdvs</groupId>
    <artifactId>DynamicJasper</artifactId>
    <version>5.3.0</version>
</dependency>
				
			

OK so now what we need to do is to make a new API endpoint in the controller directory, so that whenever a specific URL is searched, it will reach this controller which would take it further on. The function would be like this:  

				
					@PostMapping(value = "/report", produces = MediaType.APPLICATION_PDF_VALUE)
private String printReport() throws JRException, ClassNotFoundException {
    return this.employeeService.dynamicReportBuilder();
}
				
			
Controller Class API Entpoint
Controller Class API Entpoint

What’s exactly happening in this function is that it’s fetching the response from another function, which is inside the service class, and it’s returning that response to the user. Now let’s see what’s exactly happening in that function in the service class because that’s where all the report generation code is taking place.  

function inside the service class:

				
					public String dynamicReportBuilder() throws ClassNotFoundException, JRException {

    //  FETCHING ALL RECORDS OF EMPOLYEE FROM DB
    List<Employee> allEmployeeList = this.getAllData();

    FastReportBuilder drb = new FastReportBuilder();

    DynamicReport dr = drb.addColumn("ID", "eid", Long.class.getName(),10)
            .addColumn("Designation", "designation", String.class.getName(),30)
            .addColumn("DOJ", "doj", String.class.getName(),50)
            .addColumn("Name", "name", String.class.getName(),50)
            .addColumn("Salary", "salary", Long.class.getName(),50,true)
            .addGroups(2)
            .setTitle("August 2021, Employee Detail Report")
            .setSubtitle("This report was generated at " + new Date())
            .setPrintBackgroundOnOddRows(true)
            .setUseFullPageWidth(true)
            .build();

    JRDataSource ds = new JRBeanCollectionDataSource( allEmployeeList );    
    // PRIVIDING JAVA MODEL AS DATA SOURCE
    JasperPrint jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), ds);
    JasperViewer.viewReport(jp);    
    // FINALLY PRINTING THE REPORT

    return "Report Geenrated";
}
				
			

So, what’s exactly going on here?  

So, inside this function on line 85 it’s for three fetching all the data from the database table “employee” and bring them all in a list object called “allEmployeeList”. 

Next, it’s creating a FastReportBuilder object which contains all the functionality and properties that could be attached to the report during runtime, such as adding column, adding width, adding title and more. In here we’ve added five columns, whose name matches exactly from our Model class properties, then we’re also adding a title, a subtitle and then finally building it.  

Moving on to line 100, we need to specify the data source for the Jasper report and here we’ve used “JRBeanCollectionDataSource” which would essentially take in the entire model class of employee. It will compare the Model class property names with the names mentioned in the FastReportBuilder object when we were creating new columns. And then finally it will print the report, following line 102. So, let’s run the project and open up Postman for testing. 

Testing With POSTMAN

Sending HTTP request to the controller using POSTMAN
Sending HTTP request to the controller using POSTMAN

The report after generating would look something like this: 

DynamicJasper Report Generated at Runtime
DynamicJasper Report Generated at Runtime

And that’s a wrap! 

I hope you all work clear on the steps and now have a clear view on how to generate a dynamic Jasper report using models last in Java spring good, fetching data from MySQL database. Please leave a comment and share this article with others. Have a great one! 

Project File