Back-End/Spring

[Spring Boot] Spring Boot + Jasper + MySQL 데이터베이스 예제

HMHA 2023. 2. 9. 14:00
300x250
반응형

이 페이지에서는 Spring Boot + Jasper Report + MySQL 데이터베이스 예제를 살펴봅니다. 보고서는 특정 대상 및 목적을 위해 조직된 형식으로 정보를 제공하는 문서입니다. Jasper Report는 오픈 소스 Java 보고 도구입니다. PDF, Excel 등과 같은 보고서의 진실성을 생성할 수 있습니다.

유사한 게시물:  Spring Boot + Jasper 보고서 예제

우리가 만들 것

이 예제에서는 Spring Data JPA 를 사용하여 MySQL 데이터베이스 에서 직원 레코드를 가져오고 직원 목록을 보고서에 채웁니다. 마지막으로 아래와 같이 PDF 보고서를 생성합니다.

사용된 기술

이 예에서 사용된 기술 목록을 찾으십시오.

  1. STS 4
  2. 자바 8
  3. 스프링 부트 2.1.2.RELEASE
  4. 스프링 데이터 JPA
  5. Jaspersoft iReport 디자이너

종속성 필요

아래 종속성이 프로젝트 빌드 경로에 있는지 확인하십시오.

pom.xml
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
	</dependency>
</dependencies>

1. 보고서 템플릿

보고서 디자인은 JRXML 파일에 정의됩니다.

직원-rpt-database.jrxml
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="employee-rpt" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<property name="ireport.zoom" value="1.5"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="0"/>
	<parameter name="createdBy" class="java.lang.String"/>
	<field name="empNo" class="java.lang.Long"/>
	<field name="empName" class="java.lang.String"/>
	<field name="job" class="java.lang.String"/>
	<field name="salary" class="java.lang.Long"/>
	<field name="manager" class="java.lang.Long"/>
	<field name="hireDate" class="java.util.Date"/>
	<field name="commission" class="java.lang.Long"/>
	<field name="deptNo" class="java.lang.Long"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="42" splitType="Stretch">
			<staticText>
				<reportElement x="64" y="0" width="481" height="42"/>
				<textElement textAlignment="Center">
					<font size="20" isBold="true"/>
				</textElement>
				<text><![CDATA[Employee Report]]></text>
			</staticText>
		</band>
	</title>
	<columnHeader>
		<band height="61" splitType="Stretch">
			<textField>
				<reportElement x="456" y="21" width="99" height="20"/>
				<textElement/>
				<textFieldExpression><![CDATA[$P{createdBy}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="398" y="21" width="58" height="20"/>
				<textElement/>
				<text><![CDATA[Created By:]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="41" width="61" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center">
					<font size="10" isBold="true"/>
				</textElement>
				<text><![CDATA[Emp No]]></text>
			</staticText>
			<staticText>
				<reportElement x="61" y="41" width="61" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center">
					<font size="10" isBold="true"/>
				</textElement>
				<text><![CDATA[Emp Name]]></text>
			</staticText>
			<staticText>
				<reportElement x="122" y="41" width="61" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center">
					<font size="10" isBold="true"/>
				</textElement>
				<text><![CDATA[Job]]></text>
			</staticText>
			<staticText>
				<reportElement x="183" y="41" width="62" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center">
					<font size="10" isBold="true"/>
				</textElement>
				<text><![CDATA[Salary]]></text>
			</staticText>
			<staticText>
				<reportElement x="245" y="41" width="61" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center">
					<font size="10" isBold="true"/>
				</textElement>
				<text><![CDATA[Manager]]></text>
			</staticText>
			<staticText>
				<reportElement x="306" y="41" width="73" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center">
					<font size="10" isBold="true"/>
				</textElement>
				<text><![CDATA[Hire Date]]></text>
			</staticText>
			<staticText>
				<reportElement x="379" y="41" width="87" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center">
					<font size="10" isBold="true"/>
				</textElement>
				<text><![CDATA[Commission]]></text>
			</staticText>
			<staticText>
				<reportElement x="466" y="41" width="89" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center">
					<font size="10" isBold="true"/>
				</textElement>
				<text><![CDATA[Dept No]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="20" splitType="Stretch">
			<textField>
				<reportElement x="0" y="0" width="61" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center"/>
				<textFieldExpression><![CDATA[$F{empNo}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="61" y="0" width="61" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center"/>
				<textFieldExpression><![CDATA[$F{empName}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="122" y="0" width="61" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center"/>
				<textFieldExpression><![CDATA[$F{job}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="183" y="0" width="62" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center"/>
				<textFieldExpression><![CDATA[$F{salary}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="245" y="0" width="61" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center"/>
				<textFieldExpression><![CDATA[$F{manager}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="306" y="0" width="73" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center"/>
				<textFieldExpression><![CDATA[$F{hireDate}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="379" y="0" width="87" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center"/>
				<textFieldExpression><![CDATA[$F{commission}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="466" y="0" width="89" height="20"/>
				<box leftPadding="0">
					<pen lineWidth="0.25"/>
					<topPen lineWidth="0.25"/>
					<leftPen lineWidth="0.25"/>
					<bottomPen lineWidth="0.25"/>
					<rightPen lineWidth="0.25"/>
				</box>
				<textElement textAlignment="Center"/>
				<textFieldExpression><![CDATA[$F{deptNo}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
</jasperReport>

2. 법인

필드가 있는 간단한  Employee클래스를 만듭니다. 모든 필드의 getter 및 setters 메서드를 생성합니다.

Employee.java
package org.websparrow.report.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "emp")
public class Employee {
	
	@Id
	@Column(name = "empno")
	private Long empNo;
	@Column(name = "ename")
	private String empName;
	@Column(name = "job")
	private String job;
	@Column(name = "mgr")
	private Long manager;
	@Column(name = "hiredate")
	private Date hireDate;
	@Column(name = "sal")
	private Long salary;
	@Column(name = "comm")
	private Long commission;
	@Column(name = "deptno")
	private Long deptNo;

	// Generate getters and setters...
}

3. application.properties

application.properties 파일에는 데이터베이스에 연결하기 위한 모든 데이터베이스 자격 증명이 포함되어 있습니다.

application.properties
spring.datasource.url=jdbc:mysql://localhost/websparrow
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

4. 저장소

ReportRepository인터페이스 JpaRepository는 데이터베이스를 사용하여 쿼리를 확장합니다.

ReportRepository.java
package org.websparrow.report.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.websparrow.report.entity.Employee;

@Repository
public interface ReportRepository extends JpaRepository<Employee, Long> {

}

5. 서비스

EmployeeReportService클래스에서 인터페이스 ReportRepository를 자동 연결하고 클래스를findAll() method to fetch all the employees details from the database.

EmployeeReportService.java
package org.websparrow.report.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.websparrow.report.entity.Employee;
import org.websparrow.report.repository.ReportRepository;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

@Service
public class EmployeeReportService {

	@Autowired
	private ReportRepository reportRepository;

	public String generateReport() {
		try {

			List<Employee> employees = reportRepository.findAll();

			String reportPath = "F:\\Content\\Report";

			// Compile the Jasper report from .jrxml to .japser
			JasperReport jasperReport = JasperCompileManager
					.compileReport(reportPath + "\\employee-rpt-database.jrxml");

			// Get your data source
			JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(employees);

			// Add parameters
			Map<String, Object> parameters = new HashMap<>();

			parameters.put("createdBy", "Websparrow.org");

			// Fill the report
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,
					jrBeanCollectionDataSource);

			// Export the report to a PDF file
			JasperExportManager.exportReportToPdfFile(jasperPrint, reportPath + "\\Emp-Rpt-Database.pdf");

			System.out.println("Done");

			return "Report successfully generated @path= " + reportPath;
		} catch (Exception e) {
			e.printStackTrace();
			return "Error--> check the console log";
		}
	}
}

5. 컨트롤러

EmployeeReportServicein 을 Autowire하고 EmployeeReportController그  generateReport()메서드를 호출합니다.

EmployeeReportController.java
package org.websparrow.report.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.websparrow.report.service.EmployeeReportService;

@RestController
@RequestMapping("/emp")
public class EmployeeReportController {

	@Autowired
	private EmployeeReportService employeeReportService;

	@GetMapping("/report")
	public String generateReport() {

		return employeeReportService.generateReport();
	}
}

테스트

응용 프로그램을 테스트하려면 다음 단계를 따르십시오.

  1. mvn installMaven 명령 을 사용하여 애플리케이션을 빌드합니다 .
  2. 성공적인 빌드 후  Run As » Spring Boot App 애플리케이션을 실행 합니다.
  3. 응용 프로그램이 명시되면 웹 브라우저에서 http :// localhost : 8080 / emp / report URL을 누르십시오.
  4. 서비스 클래스의 지정된 위치에서 아래 PDF 보고서를 생성합니다.

참조

  1. Spring Boot + Jasper 보고서 예제
  2. Struts 2 및 Jasper 보고서 통합 예제
  3. Struts 2 및 Jasper 하위 보고서 통합 예제
 

Struts 2 and Jasper Subreports Integration Example - Websparrow

This example shows you how to integrate the Jasper Subreports with Struts 2 application to generate the dynamic reports. Jasper Subreport functionality.

websparrow.org

 

출처 : https://websparrow.org/spring/spring-boot-jasper-report-mysql-database-example

 

Spring Boot + Jasper Report + MySQL Database Example - Websparrow

This page will walk through Spring Boot + Jasper Report + MySQL Database example. Jasper Report is an open source Java reporting tool to generate PDF report

websparrow.org

 

300x250
반응형