Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 835
Piotr Avatar asked Oct 30 '22 22:10

Piotr


1 Answers

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:

  • Don't forget that getters should be public
  • More info: JavaBean Data Sources
  • The good explanation of _THIS using with samples can be found in this posts:
    1. How to access the root element of the datasource in jasperreports
    2. Passing the List of primitive type objects as datasource for subreport
    3. How do I print a list of strings contained within another list in iReport?
like image 84
Alex K Avatar answered Nov 15 '22 05:11

Alex K