Problema ao gerar relatório com JRBeanCollectionDatasource

13 respostas
douglasmanteiga

Boa tarde pessoal estou com um problema ao gerar um relatorio utilizando a classe JRBeanCollectionDataSource, segue abaixo meu código.
Classe que gera um ArrayList do banco de dados com o ID Pesquisado

public ArrayList<usuario> ArrayJasperReportJRBean(int Cod){
        AcessoDadosOracle acessoDadosOracle = new AcessoDadosOracle();
        usuario usuario = new usuario();
        ArrayList<usuario> ArraylistUsuario = new ArrayList<usuario>();
        try{
            String SQL = "SELECT USU_COD, USU_CPF, USU_NOME, USU_STATUS, USU_RG, USU_SEXO FROM USUARIO "
                    + "WHERE USU_COD = '"+Cod+"'";
            PreparedStatement statement = acessoDadosOracle.getConexao().prepareStatement(SQL);
            ResultSet resultSet = statement.executeQuery();
            
            while(resultSet.next()){
                usuario.setCodigo(resultSet.getInt("USU_COD"));
                usuario.setCPF(resultSet.getLong("USU_CPF"));
                usuario.setNome(resultSet.getString("USU_NOME"));
                usuario.setStatus(resultSet.getString("USU_STATUS"));
                usuario.setRG(resultSet.getString("USU_RG"));
                usuario.setSexo(resultSet.getString("USU_SEXO"));
                
                ArraylistUsuario.add(usuario);
            }
           
            return ArraylistUsuario;
        
        }
        catch(SQLException exSql){
            JOptionPane.showMessageDialog(null, "Erro Método ArrayJasperReportJrBean" + exSql);
            exSql.printStackTrace();
            return null;
        
        }

Agora minha Servlet tentando exibir o relatório

response.setContentType("application/pdf");
        String Codigo = request.getParameter("codigoGerarPdf");
        
        
        ArrayList<usuario> arrayListUsuario = new ArrayList<usuario>();
        classNegUsuario negUsuario = new classNegUsuario();

        try {
            arrayListUsuario = negUsuario.ArrayJasperReportJRBean(Integer.parseInt(Codigo));
            Map parametros = new HashMap();
            parametros.put("Codigo", Integer.parseInt(Codigo));
            
            JRBeanCollectionDataSource jrBeanCollec = new JRBeanCollectionDataSource(arrayListUsuario);
            JasperPrint jasperPrint = JasperFillManager.fillReport(getServletContext().getRealPath("/relatorio/usuarioRelatorioJRBean.jasper"), parametros, jrBeanCollec);
            if (jasperPrint != null) {
                byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
                response.setContentLength(bytes.length);
                ServletOutputStream ouputStream = response.getOutputStream();
                ouputStream.write(bytes, 0, bytes.length);
                ouputStream.flush();
                ouputStream.close();
            }

Erro que está aparecendo ao tentar Gerar
net.sf.jasperreports.engine.JRException: Error retrieving field value from bean: Codigo

Estou utilizando o Ireport 3.7
E no meu arquivo Ireport.jrxml só criei os campo no Fields com o nome da minha Classe Get e SET
Exemplo essa classe é o que o array recebe

public class usuario {
    private int Codigo;
    private Long CPF;
    private String Nome;
    private String Status;
    private byte[] FotoByte;
    private String RG;
    private String Sexo;

    /**
     * @return the Codigo
     */
    public int getCodigo() {
        return Codigo;
    }

13 Respostas

darklordkamui

o seu metodo está fazendo a busca corretamente?
ta trazendo algum resultado?

darklordkamui

acho que sei qual foi seu erro…

Voce criou em Parameters a variavel chamada “Codigo” e com o tipo Integer em propriedades?

acredito que sejá isso o seu erro

douglasmanteiga

Obrigado pela resposta, meu método retorna um array com os dados do banco corretamente(já testei para ver o retorno), e meu Field do Relatório está como tipo Int sim… mas alguma sugestão? valeu.

J

seta o nome do campo como codigo em vez de Codigo, dai vai funcionar dai :smiley:

J

use codigo ao invés de Codigo

darklordkamui

então… ai é que ta o problema…

vc criou o field Codigo… quando na verdade é para vc criar um Parameters Codigo… pois se vc olhar bem… vc adiciona

Map parametros = new HashMap(); parametros.put("Codigo", Integer.parseInt(Codigo));

e isso aqui não é um field… são variaveis estaticas que você passa ao relatorio que sempre seram aquele valor… então nem precisa fazer a transformação de String para Integer… basta ir no relatorio e colocar como parameters Codigo com a propriedade String =P

muda isso no jasper que ira funcionar

só para ficar mais claro…

no Report Inspector tem a seguinte estrutura…

Nome do Relatorio
Style
Parameters
Fields
e etc…

apaga o Codigo do fields e cria no parameters =P

ou apaga esse parametros.put(“Codigo”, Integer.parseInt(Codigo));

e ira funcionar =P

douglasmanteiga

Agora eu percebi uma coisa, essa linha do Map eu não preciso pois eu pesquiso já um ID pelo request e jogo no meu array do banco para consultar,
o meu retorno é um array de cliente, mas quando eu jogo ele no meu JASPER ele da o mesmo erro.
Error retrieving value from bean: Código
Será que montei meu relatório errado?
Segue abaixo o Código XML do meu relatório… bom o que tenho nele… vários FIelds com o mesmo nome da minha classe usuario… que são os get e set…

<?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="report name" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<property name="ireport.zoom" value="1.0"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="0"/>
	<queryString>
		<![CDATA[]]>
	</queryString>
	<field name="Codigo" class="java.lang.Integer"/>
	<field name="CPF" class="java.math.BigDecimal"/>
	<field name="Nome" class="java.lang.String"/>
	<field name="Status" class="java.lang.String"/>
	<field name="RG" class="java.lang.String"/>
	<field name="Sexo" class="java.lang.String"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="15" splitType="Stretch"/>
	</title>
	<pageHeader>
		<band height="34" splitType="Stretch">
			<staticText>
				<reportElement x="150" y="0" width="293" height="27" forecolor="#FF3333"/>
				<textElement>
					<font size="18"/>
				</textElement>
				<text><![CDATA[Relatório de Usuário utilizando JR Bean]]></text>
			</staticText>
		</band>
	</pageHeader>
	<columnHeader>
		<band height="24" splitType="Stretch"/>
	</columnHeader>
	<detail>
		<band height="125" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="0" width="100" height="20" forecolor="#FF0000" backcolor="#00FF33"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[Código]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="20" width="100" height="20" forecolor="#FF0000" backcolor="#00FF33"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[CPF]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="40" width="100" height="20" forecolor="#FF0000"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[Nome]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="60" width="100" height="20" forecolor="#FF0000" backcolor="#00FF33"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[Status]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="100" width="100" height="20" forecolor="#FF0000" backcolor="#00FF33"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[Sexo]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="80" width="100" height="20" forecolor="#FF0000"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[RG]]></text>
			</staticText>
			<textField>
				<reportElement x="100" y="0" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.Integer"><![CDATA[$F{Codigo}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="20" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{CPF}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="40" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{Nome}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="60" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{Status}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="80" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{RG}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="100" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{Sexo}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<columnFooter>
		<band height="45" splitType="Stretch">
			<textField>
				<reportElement x="272" y="25" width="241" height="20"/>
				<textElement textAlignment="Right"/>
				<textFieldExpression class="java.lang.String"><![CDATA["Página "+$V{PAGE_NUMBER}+" de"]]></textFieldExpression>
			</textField>
			<textField evaluationTime="Report">
				<reportElement x="513" y="25" width="40" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
			</textField>
		</band>
	</columnFooter>
	<pageFooter>
		<band height="54" splitType="Stretch"/>
	</pageFooter>
	<summary>
		<band height="42" splitType="Stretch"/>
	</summary>
</jasperReport>
darklordkamui

entao vc removeu a linha do codigo e testou denovo?

pq esse erro é justamente por vc ta passando uma variavel que nao existe no relatorio

douglasmanteiga

Sim removi a linha e mesmo assim deu o erro… será que no meu Relatório eu tenho que ler o array qe estou recebendo e jogar nos FIeld? pq eu só criei os fields…

darklordkamui

achei um erro no cpf… vc colocou ele como BigDecimal no jasper… quando na verdade tem que ser Long igual na entidade…

ve se é isso

douglasmanteiga

Bouaa… mas não é isso pois o erro já acontece no código… nem chega no CPF… alterei aqui mas mesma coisa =/

darklordkamui

posta o stack completo porfavor

darklordkamui

bom fiz um teste aqui e conseguir rodar normalmente... porem eu fiz mudança na estrutura... vou postar como fiz...

tudo que fiz foi no linux... por isso depois altera os caminhos para o padrao windows ok?

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
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;

public class Teste {

	public static void main(String[] args) throws FileNotFoundException, InterruptedException {
		Map<String, Object> param = new HashMap<String, Object>();
		String output = "/home/MeuUsuario/output/teste.pdf";
		String reportPath = "/home/MeuUsuario/output/report1.jrxml";

		param.put("REPORT_LOCALE", new Locale("pt", "BR"));

		JasperReport jasperReport;
		JasperPrint jasperPrint;
		try {

			List<Usuario> dataSource = new ArrayList<Usuario>();
			Usuario usuario = new Usuario();
			usuario.setCodigo(1);
			usuario.setNome("Blaa");
			usuario.setRg("blalalalal");
			usuario.setSexo("bla bla bla");
			usuario.setStatus("HAHAHA");

			dataSource.add(usuario);

			jasperReport = JasperCompileManager.compileReport(new FileInputStream(new File(reportPath)));
			jasperPrint = JasperFillManager.fillReport(jasperReport, param, new JRBeanCollectionDataSource(dataSource));
			JasperExportManager.exportReportToPdfFile(jasperPrint, output);

		} catch (JRException e) {
			e.printStackTrace();
		}
	}
}

e a entidade ...

public class Usuario {

	private int codigo;
	private Long cpf;
	private String nome;
	private String status;
	private byte[] fotoByte;
	private String rg;
	private String sexo;

	/**
	 * @return the codigo
	 */
	public int getCodigo() {
		return codigo;
	}

	/**
	 * @param codigo
	 *            the codigo to set
	 */
	public void setCodigo(int codigo) {
		this.codigo = codigo;
	}

	/**
	 * @return the cpf
	 */
	public Long getCpf() {
		return cpf;
	}

	/**
	 * @param cpf
	 *            the cpf to set
	 */
	public void setCpf(Long cpf) {
		this.cpf = cpf;
	}

	/**
	 * @return the nome
	 */
	public String getNome() {
		return nome;
	}

	/**
	 * @param nome
	 *            the nome to set
	 */
	public void setNome(String nome) {
		this.nome = nome;
	}

	/**
	 * @return the status
	 */
	public String getStatus() {
		return status;
	}

	/**
	 * @param status
	 *            the status to set
	 */
	public void setStatus(String status) {
		this.status = status;
	}

	/**
	 * @return the fotoByte
	 */
	public byte[] getFotoByte() {
		return fotoByte;
	}

	/**
	 * @param fotoByte
	 *            the fotoByte to set
	 */
	public void setFotoByte(byte[] fotoByte) {
		this.fotoByte = fotoByte;
	}

	/**
	 * @return the rg
	 */
	public String getRg() {
		return rg;
	}

	/**
	 * @param rg
	 *            the rg to set
	 */
	public void setRg(String rg) {
		this.rg = rg;
	}

	/**
	 * @return the sexo
	 */
	public String getSexo() {
		return sexo;
	}

	/**
	 * @param sexo
	 *            the sexo to set
	 */
	public void setSexo(String sexo) {
		this.sexo = sexo;
	}

}

e o jasper... com minhas alterações...

<?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="report name" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<property name="ireport.zoom" value="1.0"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="0"/>
	<queryString>
		<![CDATA[]]>
	</queryString>
	<field name="codigo" class="java.lang.Integer"/>
	<field name="cpf" class="java.lang.Long"/>
	<field name="nome" class="java.lang.String"/>
	<field name="status" class="java.lang.String"/>
	<field name="rg" class="java.lang.String"/>
	<field name="sexo" class="java.lang.String"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="15" splitType="Stretch"/>
	</title>
	<pageHeader>
		<band height="34" splitType="Stretch">
			<staticText>
				<reportElement x="150" y="0" width="293" height="27" forecolor="#FF3333"/>
				<textElement>
					<font size="18"/>
				</textElement>
				<text><![CDATA[Relatório de Usuário utilizando JR Bean]]></text>
			</staticText>
		</band>
	</pageHeader>
	<columnHeader>
		<band height="24" splitType="Stretch"/>
	</columnHeader>
	<detail>
		<band height="125" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="0" width="100" height="20" forecolor="#FF0000" backcolor="#00FF33"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[Código]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="20" width="100" height="20" forecolor="#FF0000" backcolor="#00FF33"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[CPF]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="40" width="100" height="20" forecolor="#FF0000"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[Nome]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="60" width="100" height="20" forecolor="#FF0000" backcolor="#00FF33"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[Status]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="100" width="100" height="20" forecolor="#FF0000" backcolor="#00FF33"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[Sexo]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="80" width="100" height="20" forecolor="#FF0000"/>
				<textElement>
					<font size="12" isBold="true"/>
				</textElement>
				<text><![CDATA[RG]]></text>
			</staticText>
			<textField>
				<reportElement x="100" y="0" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.Integer"><![CDATA[$F{codigo}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="20" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.Long"><![CDATA[$F{cpf}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="40" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{nome}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="60" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{status}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="80" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{rg}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="100" y="100" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{sexo}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<columnFooter>
		<band height="45" splitType="Stretch">
			<textField>
				<reportElement x="272" y="25" width="241" height="20"/>
				<textElement textAlignment="Right"/>
				<textFieldExpression class="java.lang.String"><![CDATA["Página "+$V{PAGE_NUMBER}+" de"]]></textFieldExpression>
			</textField>
			<textField evaluationTime="Report">
				<reportElement x="513" y="25" width="40" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
			</textField>
		</band>
	</columnFooter>
	<pageFooter>
		<band height="54" splitType="Stretch"/>
	</pageFooter>
	<summary>
		<band height="42" splitType="Stretch"/>
	</summary>
</jasperReport>
Criado 6 de julho de 2012
Ultima resposta 6 de jul. de 2012
Respostas 13
Participantes 3