Piotr
Piotr

Reputation: 87

How to get the value of complex JavaBean

I have a .jrxml file and I would like to pass some params from the code to it. I have an Order class that has fields like double price, int quantity and Product product. The situation is simple, when i need to pass price or quantity, I just do something like this:

<textFieldExpression class = "java.lang.Integer">
   <![CDATA[$F{quantity}]]>
</textFieldExpression>

The problem appears when I try to pass product.getName(). I tried something like:

<textFieldExpression class = "java.lang.String">
   <![CDATA[$F{product}.getName()]]>
</textFieldExpression>

and many others but I keep getting error: net.sf.jasperreports.engine.design.JRValidationException: Report design not valid : 1. Field not found : product

Do you have any idea how to solve this problem?

Upvotes: 5

Views: 247

Answers (1)

Alex K
Alex K

Reputation: 22857

For example you have a pair of JavaBeans (POJO):

public class Order {

    private double price;
    private int quantity;
    private Product product;
    // public getters 
}

public class Product {

    private String name;
    // public getters 
}

and you declare report's datasource in the manner like this: (yes, I like Guava)

JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(Lists.newArrayList(ImmutableList.<Order>builder()
        .add(new Order(1000.2, 10, new Product("Phone")))
        .add(new Order(10200.0, 2, new Product("Tv")))
        .build()));

In case using this fields declaration:

<field name="order" class="java.lang.Object">
    <fieldDescription><![CDATA[_THIS]]></fieldDescription>
</field>
<field name="price" class="java.lang.Double"/>
<field name="quantity" class="java.lang.Integer"/>
<field name="productName" class="java.lang.String">
    <fieldDescription><![CDATA[product.name]]></fieldDescription>
</field>

you can use such expressions:

<textField>
    <reportElement x="0" y="0" width="100" height="30"/>
    <textFieldExpression><![CDATA[$F{price}]]></textFieldExpression>
</textField>
<textField>
    <reportElement x="100" y="0" width="100" height="30"/>
    <textFieldExpression><![CDATA[$F{quantity}]]></textFieldExpression>
</textField>
<textField>
    <reportElement x="200" y="0" width="100" height="30"/>
    <textFieldExpression><![CDATA[$F{productName}]]></textFieldExpression>
</textField>

Note:

Upvotes: 3

Related Questions